我有多维数组:-
$first= array(
[51581481] => array(
'title' => 'Nike - L',
'price' => '300.00',
'vendor' => 'Vicky Fashion Point',
'quantity' => -23,
),
[45747894] => array(
'title' => 'Honor Band A (Black) - Default Title',
'price' => '2249.00',
'vendor' => 'Honor',
'quantity' => 8,
)
);
$second = array(
0 => '45747894',
1 => '713776113',
);
我想比较两个数组并首先从数组中获取差异数据。我正在使用 array_diff 函数
$arr_diff= array_diff($first, $second);
此错误显示:-
ERROR: Array to string conversion
就这样
$arr_diff = array_diff_key($first, array_flip($second));
技巧是array_flip第二个数组并使用array_diff_key
$first = array(
51581481 => array(
'title' => 'Nike - L',
'price' => '300.00',
'vendor' => 'Vicky Fashion Point',
'quantity' => -23,
),
45747894 => array(
'title' => 'Honor Band A (Black) - Default Title',
'price' => '2249.00',
'vendor' => 'Honor',
'quantity' => 8,
),
);
$second = array(
0 => 45747894,
1 => 713776113,
);
var_dump(array_diff_key($first, array_flip($second)));
您可以使用
array_search()
和 unset()
来区分两个数组。
$first= array( "51581481"=>array(
'title' => 'Nike - L',
'price' => '300.00',
'vendor' => 'Vicky Fashion Point',
'quantity' => -23,
),
"45747894"=>array(
'title' => 'Honor Band A (Black) - Default Title',
'price' => '2249.00',
'vendor' => 'Honor',
'quantity' => 8,
)
);
$second=array("0" => '45747894',
"1" => '713776113',
);
$array_diff = [];
foreach($first as $key => $val)
{
if(array_search($key, $second) !== false)
{
unset($first[$key]);//remove matched key record
}
}
echo '<pre>';print_r($first);echo '</pre>';
预期输出:
Array
(
[51581481] => Array
(
[title] => Nike - L
[price] => 300.00
[vendor] => Vicky Fashion Point
[quantity] => -23
)
)
作为一个简单的解决方案,循环遍历第一个数组并检查第二个数组中是否存在该键以获得差异。
$diff = [];
foreach ($first as $key => $value) {
if(!in_array($key, $second)) {
$diff[$key] = $value;
}
}