比较两个数组的最快方法 key_values PHP

fastest way to compare two array key_values PHP

我有如下两个变量

$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
 ],
];

对于一个日志系统,我希望变量 $items1 作为一个引用,并找到它对 $items2 变量的更改,最后得到以下输出:

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

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

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

对于日志系统可能是更好的建议格式,感谢您的帮助

工作示例

$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);