我有以下两个数组:
数组1
Array
(
[0] => 6012
[1] => 7792
)
数组2
Array
(
[6012] => Array
(
[title] => COIN Group
[nid] => 6012
)
[7792] => Array
(
[title] => fdsfsdafdsa
[nid] => 7792
)
[4689] => Array
(
[title] => General Group
[nid] => 4689
)
[6784] => Array
(
[title] => Invitation to join the group Applied Economics for Managers
[nid] => 6784
)
)
我需要比较这两个数组并找出数组1和数组2之间值的差异。我的输出需要看起来像这样:
Array
(
[4689] => Array
(
[title] => General Group
[nid] => 4689
)
[6784] => Array
(
[title] => Invitation to join the group Applied Economics for Managers
[nid] => 6784
)
)
如何使用PHP完成这项工作?
答案 0 :(得分:1)
$compare_array1 = array_values($array1);
$compare_array2 = array_keys($array2);
$diff_keys = array_diff($compare_array2, $compare_array1);
$result = array();
foreach ($diff_keys as $key)
$result[$key] = $array2[$key];
答案 1 :(得分:0)
伪代码:
result = array();
foreach array2 as key => value {
if (in_array(key, array1) {
result[key] = value;
}
}
答案 2 :(得分:0)
function diffArrays($array1,$array2){
foreach($array1 as $key)
unset($array2[$key];
return $array2;
}
或
function diffArrays2($array1,$array2){
return array_diff_key($array2,array_flip($array1));