[英]PHP - Compare two arrays
These are my 2 arrays: 这些是我的2个数组:
Array
(
[25] => Array
(
[items_to_give] => Array
(
[0] => Array
(
[xx] => xx
[xx] => xx
)
)
[items_to_get] => Array
(
[0] => Array
(
[xx] => xx
[xx] => xx
)
)
)
[26] => Array
(
[items_to_give] => Array
(
[0] => Array
(
[xx] => xx
[xx] => xx
)
)
[items_to_get] => Array
(
[0] => Array
(
[xx] => xx
[xx] => xx
)
)
)
[36] => Array
(
[items_to_give] => Array
(
[0] => Array
(
[xx] => xx
[xx] => xx
)
)
[items_to_get] => Array
(
[0] => Array
(
[xx] => xx
[xx] => xx
)
)
)
)
and 和
Array
(
[25] => Array
(
[items_to_give] => Array
(
[0] => Array
(
[xx] => xx
[xx] => xx
)
)
[items_to_get] => Array
(
[0] => Array
(
[xx] => xx
[xx] => xx
)
)
)
[26] => Array
(
[items_to_give] => Array
(
[0] => Array
(
[xx] => xx
[xx] => xx
)
)
[items_to_get] => Array
(
[0] => Array
(
[xx] => xx
[xx] => xx
)
)
)
[30] => Array
(
[items_to_give] => Array
(
[0] => Array
(
[xx] => xx
[xx] => xx
)
)
[items_to_get] => Array
(
[0] => Array
(
[xx] => xx
[xx] => xx
)
)
)
)
And now i want to compare these arrays and return all arrayitems which are contained in both arrays. 现在我想比较这些数组并返回两个数组中包含的所有arrayitem。 In the example these are [25] and [26].
在示例中,这些是[25]和[26]。
So the returned array should look like this (As i said [25] and [26] are contained in both arrays so its returned): 因此,返回的数组应如下所示(正如我所说的[25]和[26]都包含在两个数组中,因此返回了):
Array
(
[25] => Array
(
[items_to_give] => Array
(
[0] => Array
(
[xx] => xx
[xx] => xx
)
)
[items_to_get] => Array
(
[0] => Array
(
[xx] => xx
[xx] => xx
)
)
)
[26] => Array
(
[items_to_give] => Array
(
[0] => Array
(
[xx] => xx
[xx] => xx
)
)
[items_to_get] => Array
(
[0] => Array
(
[xx] => xx
[xx] => xx
)
)
)
)
What i already tried: 我已经尝试过的
$result = array_map("unserialize", array_intersect($this->serialize_array_values($array1),$this->serialize_array_values($array2)));
function serialize_array_values($arr){
foreach($arr as $key=>$val){
sort($val);
$arr[$key]=serialize($val);
}
return $arr;
}
But this returns the array in the wrong format. 但这会以错误的格式返回数组。 The [items_to_give] and [items_to_get] are getting converted to the index [0] and [1] which is undesirable.
[items_to_give]和[items_to_get]被转换为索引[0]和[1],这是不希望的。
I want the array to stay as he is when returned that means i need [items_to_give] and [items_to_get] instead of indexes [0] and [1] 我希望数组在返回时保持原样 ,这意味着我需要[items_to_give]和[items_to_get]而不是索引[0]和[1]
What are other possible solutions? 还有哪些其他可能的解决方案? Thanks for solutions.
感谢您的解决方案。
Try this function: 试试这个功能:
function my_array_diff($arr1, $arr2)
{
$res = array();
foreach ($arr1 as $val1) {
$val1 = serialize($val1);
foreach ($arr2 as $key2 => $val2) {
if (serialize($val2) == $val1) {
$res[$key2] = $val2;
}
}
}
return $res;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.