我有两个二维数组。
$array1 = [
['quantity' => 13, 'idname' => 3, 'x_name' => 'Name-3'],
['quantity' => 5, 'idname' => 4, 'x_name' => 'Name-4']
];
$array2 = [
['id_x' => 3, 'x_name' => 'Name-3', 'id_l' => 4],
['id_x' => 4, 'x_name' => 'Name-4', 'id_l' => 8],
['id_x' => 5, 'x_name' => 'Name-5', 'id_l' => 7],
['id_x' => 6, 'x_name' => 'Name-6', 'id_l' => 5]
];
如果第一个数组中的行包含两个对应的列值,我需要从第二个数组中删除行。
Array1[][idname] = Array2[][id_x]
和Array1[][x_name] = Array2[][x_name]
(当然)我想要的输出:
[
['id_x' => 5, 'x_name' => 'Name-5', 'id_l' => 7],
['id_x' => 6, 'x_name' => 'Name-6', 'id_l' => 5]
]
您可以使用嵌套的 foreach 循环。如果在 array1 中找到 array2 当前元素的值,则删除该元素:
foreach($array2 as $key => $value){
foreach($array1 as $val){
if($value['x_name']==$val['x_name']){
unset($array2[$key]);
$break;
}
}
}
var_dump($array2);
<?php
$arr1 = Array();
$arr1[] = Array('quantity' => 13, 'idname' => 3, 'x_name' => 'Name-3');
$arr1[] = Array('quantity' => 5, 'idname' => 4, 'x_name' => 'Name-4');
$arr2 = Array();
$newTemp = Array();
$arr2[] = Array('id_x' => 3, 'x_name' => 'Name-3', 'id_l' => 4);
$arr2[] = Array('id_x' => 4, 'x_name' => 'Name-4', 'id_l' => 8);
$arr2[] = Array('id_x' => 5, 'x_name' => 'Name-5', 'id_l' => 7);
$arr2[] = Array('id_x' => 6, 'x_name' => 'Name-6', 'id_l' => 5);
$newTemp = $arr2;
foreach ($arr1 as $subArray1) {
foreach ($arr2 as $key => $subArray2) {
if ($subArray1['x_name']==$subArray2['x_name']) {
unset($newTemp[$key]);
break;
}
}
}
print_r($arr1);
print_r($arr2);
print_r($newTemp);
?>
由于
array_u*()
函数的回调不知道要比较的两个变量的源数组,因此比较脚本必须尝试像访问一个数组一样访问数据,然后在需要时回退到另一个数组。
使用太空船运算符对由指定数据点组成的两个临时数组进行三向比较。 演示
var_export(
array_udiff(
$array2,
$array1,
fn($a, $b) => [$a['idname'] ?? $a['id_x'], $a['x_name']]
<=>
[$b['idname'] ?? $b['id_x'], $b['x_name']]
)
);
输出:
array (
2 =>
array (
'id_x' => 5,
'x_name' => 'Name-5',
'id_l' => 7,
),
3 =>
array (
'id_x' => 6,
'x_name' => 'Name-6',
'id_l' => 5,
),
)