似乎我读到的用于比较数组的每个PHP函数(array_diff(),array_intersect()等)都比较了数组元素的存在.
给定两个具有相同结构的多维数组,您如何列出值的差异?
例
数组1
[User1] => Array ([public] => 1
[private] => 1
[secret] => 1
)
[User2] => Array ([public] => 1
[private] => 0
[secret] => 0
)
数组2
[User1] => Array ([public] => 1
[private] => 0
[secret] => 1
)
[User2] => Array ([public] => 1
[private] => 0
[secret] => 0
)
区别
[User1] => Array ([public] => 1
[private] => 0 //this value is different
[secret] => 1
)
所以我的结果是 – “在所有用户中,User1已经改变,不同之处在于private是0而不是1.”
解决方法:
一种方法是编写一个函数来做类似的事情.
function compareArray ($array1, $array2)
{
foreach ($array1 as $key => $value)
{
if ($array2[$key] != $value)
{
return false;
}
}
return true;
}
您可以轻松地扩充该函数以返回两者中的差异数组.
编辑 – 这是一个精致的版本,更接近你正在寻找的东西:
function compareArray ($array1, $array2)
{
var $differences;
foreach ($array1 as $key => $value)
{
if ($array2[$key] != $value)
{
$differences[$key][1] = $value;
$differences[$key][2] = $array2[$key];
}
}
if (sizeof($differences) > 0)
{
return $differences;
}
else
{
return true;
}
}
标签:php,arrays,comparison
来源: https://codeday.me/bug/20190607/1193180.html