Home > Back-end >  fastest way to compare two array key_values PHP
fastest way to compare two array key_values PHP

Time:03-13

I have two variables like the following

$items1 = 
[
 [
  "p_id" => 1000,
  "value"=> 25
 ],
 [
  "p_id" => 2000,
  "value"=> 15
 ],
 [
  "p_id" => 3000,
  "value"=> 23
 ],
];

$items2 = 
[
 [
  "p_id" => 1000,
  "value"=> 5
 ],
 [
  "p_id" => 4000,
  "value"=> 12
 ],
];

For a logging system, I want variable $items1 to be a reference and find its changes to the $items2 variable and finally have the following output:

$deleted = [
 [
  "p_id" => 2000,
  "value"=> 15
 ]
];

$added = [
 [
  "p_id" => 4000,
  "value"=> 12
 ],
];

$changed = [
  [
   "p_id" => 1000,
   "value"=> 5
  ],
 ];

For a logging system may be a better suggested format, thank you for your help

CodePudding user response:

working example

$items1 = 
[
 [
  "p_id" => 1000,
  "value"=> 25
 ],
 [
  "p_id" => 2000,
  "value"=> 15
 ],
 [
  "p_id" => 3000,
  "value"=> 23
 ],
];

$items2 = 
[
 [
  "p_id" => 1000,
  "value"=> 5
 ],
 [
  "p_id" => 4000,
  "value"=> 12
 ],
];

function keyedByPidArray($items) {
   $arr = [];
   foreach($items as $item) {
      $arr[$item['p_id']] = $item;
    }
   
    return $arr;
}

function changedItems($items1, $items2) {
  $changed = [];
  foreach($items1 as $item1) {
    foreach($items2 as $k => $item2) {
        if(($item1["p_id"] === $item2["p_id"]) && ($item1["value"] !== $item2["value"])) {
            $changed[] = $item2;
            unset($items2[$k]);
            break;
        }
    }
  }
  
  return $changed;
}

$keyedByPidArr1 = keyedByPidArray($items1);
$keyedByPidArr2 = keyedByPidArray($items2);

$pids1 = array_column($items1, 'p_id');
$pids2 = array_column($items2, 'p_id');

$added = array_intersect_key($keyedByPidArr2, array_flip(array_diff($pids2, $pids1)));
$deleted = array_intersect_key($keyedByPidArr1, array_flip(array_diff($pids1, $pids2)));

$changed = changedItems($items1, $items2);

print_r($added);
print_r($deleted);
print_r($changed);
  • Related