在项目中经常遇到需要动态编辑特定事物的一组属性,这时就涉及到新选择的值与旧值对比更新,记录在项目中采用的一种方法,主要采用 PHP array_filter() 函数:
$delete_array = $add_new_array = array(); $array1 = array( array(‘user_id‘ => 1, ‘user_name‘ => ‘一00一‘, ‘corp_id‘ => 1), array(‘user_id‘ => 2, ‘user_name‘ => ‘二00二‘, ‘corp_id‘ => 1), array(‘user_id‘ => 3, ‘user_name‘ => ‘三00三‘, ‘corp_id‘ => 1), ); $array2 = array( array(‘user_id‘ => 1, ‘user_name‘ => ‘一00一‘), array(‘user_id‘ => 2, ‘user_name‘ => ‘二00二‘), // array(‘user_id‘ => 3, ‘user_name‘ => ‘三00三‘), array(‘user_id‘ => 4, ‘user_name‘ => ‘四00四‘), ); $delete_array = array_filter($array1, function ($v, $k) use ($array2) { foreach ($array2 as $key => $val) { if ($val[‘user_id‘] == $v[‘user_id‘]) { return false; } } return true; }, ARRAY_FILTER_USE_BOTH); $add_new_array = array_filter($array2, function ($v, $k) use ($array1) { foreach ($array1 as $key => $val) { if ($val[‘user_id‘] == $v[‘user_id‘]) { return false; } } return true; }, ARRAY_FILTER_USE_BOTH); echo ‘delete_array:‘; print_r(array_values($delete_array)); echo "\n", ‘add_new_array:‘; print_r(array_values($add_new_array));
效果如下: