我有 2 个多维数组。
Array1 包含一些可用名称:
Array1
(
[0] => Array
(
[quantity] => 13
[idname] => 3
[x_name] => Name-3
)
[1] => Array
(
[quantity] => 5
[idname] => 4
[x_name] => Name-4
)
)
和 Array2 包含所有可用名称:
Array2
(
[0] => Array
(
[id_x] => 3
[x_name] => Name-3
[id_l] => 4
)
[1] => Array
(
[id_x] => 4
[x_name] => Name-4
[id_l] => 8
)
[2] => Array
(
[id_x] => 5
[x_name] => Name-5
[id_l] => 7
)
[3] => Array
(
[id_x] => 6
[x_name] => Name-6
[id_l] => 5
)
)
数组1[][idname] = 数组2[][id_x] 和 Array1[][x_name] = Array2[][x_name] (ofc...)
我想要的输出是 Array2 中 Array1 不包含的每个元素......所以:
Arraydesire
(
[0] => Array
(
[id_x] => 5
[x_name] => Name-5
[id_l] => 7
)
[1] => Array
(
[id_x] => 6
[x_name] => Name-6
[id_l] => 5
)
)
我尝试使用 array_intersect 但没有成功。 感谢您的帮助。
您可以使用嵌套的 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*()
函数的回调不知道要比较的两个变量的源数组,因此比较脚本必须尝试像访问一个数组一样访问数据,然后在需要时回退到另一个数组。
使用 spaceship 运算符对由指定数据点组成的两个临时数组进行三向比较。 演示
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,
),
)