有人知道如何获取array_diff之前和之后的函数。
var_dump(array_diff(['a' => 'b', 'c' => 'x'], ['a' => 'c', 'c' => 'x']));
结果是
array(1) {
'a' =>
string(1) "b"
}
我想要像
这样的东西array(2) {
[0] =>
array(1) {
'a' =>
string(1) "b"
}
[1] =>
array(1) {
'a' =>
string(1) "c"
}
}
是否有功能或为您提供一些代码?
提前致谢!
答案 0 :(得分:0)
尝试使用array_diff_assoc - array_diff仅比较值。
你可以这样做:
$arr1 = ['a' => 'b', 'c' => 'x'];
$arr2 = ['a' => 'c', 'c' => 'x'];
$diffs = [
array_diff_assoc($arr1, $arr2),
array_diff_assoc($arr2, $arr1)
];
答案 1 :(得分:0)
试试这个:你可以对那些键进行区分,因为在你的数组是数组的键之后
$newArr = [
['a' => 'b', 'c' => 'x'],
['a' => 'c', 'c' => 'x']
];
$a = array_diff_assoc($newArr[0], $newArr[1]); //differentiate the 1st and 2nd keys
$b = array_diff_assoc($newArr[1], $newArr[0]); //differentiate the 2nd keys to the 1st keys
$diff = [$a, $b]; //then store the result to an array
echo '<pre>';
var_dump($diff);
这是输出:
array(2) {
[0]=>
array(1) {
["a"]=>
string(1) "b"
}
[1]=>
array(1) {
["a"]=>
string(1) "c"
}
}
或者如果它是一个数组数组:
//all keys are 0 and 1 because you're differentiate only two keys in one multi-dimensional array
$arr2= [
0 => [
['a' => 'b', 'c' => 'x'],
['a' => 'c', 'c' => 'x']
],
1 => [
['d' => 'e', 'c' => 'y'],
['d' => 'b', 'c' => 'y']
]
];
foreach($arr2 as $key => $val){
$a[] = array_diff_assoc($val[0], $val[1]);
$b[] = array_diff_assoc($val[1], $val[0]);
}
var_dump($diff);
输出:
array(2) {
[0]=>
array(2) {
[0]=>
array(1) {
["a"]=>
string(1) "b"
}
[1]=>
array(1) {
["d"]=>
string(1) "e"
}
}
[1]=>
array(2) {
[0]=>
array(1) {
["a"]=>
string(1) "c"
}
[1]=>
array(1) {
["d"]=>
string(1) "b"
}
}
}