我有2个数组
array:23 [▼
"cpe_mac" => "298639133839"
"bandwidth_max_up" => 30000
"bandwidth_max_down" => 50000
"filter_icmp_inbound" => true
"dmz_enabled" => false
"dmz_host" => "http:\/\/ddd.com"
"vlan_id" => 2
"dns" => array:2 [▶]
"xdns_mode" => 0
"cfprofileid" => 11111
"stub_response" => "0"
"acl_mode" => 1
"portal_url" => "http:\/\/portal.com"
"fullbandwidth_max_up" => 1000000
"fullbandwidth_max_down" => 2000000
"fullbandwidth_guaranty_up" => 300000
"fullbandwidth_guaranty_down" => 400000
"account_id" => 1000
"location_id" => 3333
"network_count" => 3
"group_name" => "test_group"
"vse_id" => 20
"firewall_enabled" => false
]
array:23 [▼
"cpe_mac" => "a0a1a2a3a4a5"
"bandwidth_max_up" => 300000
"bandwidth_max_down" => 500000
"filter_icmp_inbound" => true
"dmz_enabled" => false
"dmz_host" => "http] = \/\/ddd.com"
"vlan_id" => 2
"dns" => array:2 [▶]
"xdns_mode" => 0
"cfprofileid" => 11111
"stub_response" => ""
"acl_mode" => 1
"portal_url" => "http] = \/\/portal.com"
"fullbandwidth_max_up" => 1000000
"fullbandwidth_max_down" => 2000000
"fullbandwidth_guaranty_up" => 300000
"fullbandwidth_guaranty_down" => 400000
"account_id" => 1234
"location_id" => 3333
"network_count" => 3
"group_name" => "test_group"
"vse_id" => 20
"firewall_enabled" => false
]
我用眼睛看过它们无数次,它们对我来说看起来都是一样的,除了它们的价值。然后,我以编程方式比较它们,
$equal = ($cpe == $sample );
dd($equal); // false
我认为,它会返回false
,因为它们的值不同。我说得对吗?
length
key
data-type
不同,我怎样才能找出到底是什么让它们不同?
例如
$sample["cpe_mac"] == "a0a1a2a3a4a5"
和
$cpe["cpe_mac"] == "298639133839"
。还有
$sample["bandwidth_max_up"] == 300000
和
$cpe["bandwidth_max_up"] == 30000
。只需查看数组,您就可以立即知道它们不相等,因此没有逻辑理由相信
$cpe == $sample
应该是
true
。
此外,array_diff
将值作为字符串进行比较。你拥有的是一个多维数组。因此不可能用
array_diff
来计算数组中非标量元素的差异。
注:手册中还详细阐述了第二个注释...此函数
仅检查 n 维数组的一维。当然,您可以使用
array_diff($array1[0], $array2[0]);
检查更深的维度。
注:当且仅当
if (string) $elem1 === (string) $elem2
时,两个元素被视为相等。换句话说:当字符串表示相同时。
示例
$diff = [];
foreach($cpe as $key => $value) {
if (array_key_exists($key, $sample) && $sample[$key] !== $value) {
$diff[$key] = $sample[$key];
}
}
您也可以将其编写为递归函数来计算 n 维数组内的差异...
function array_diff_recursive(Array $a, Array $b, Array $diff = [])
{
foreach($a as $k => $v) {
if (!array_key_exists($k, $b)) {
$diff[$k] = $v;
continue;
}
if (is_array($v)) {
$diff += array_diff_recursive($v, $b[$k], $diff);
} else {
if ($v !== $b[$k]) { // you could change this to == for loose comparison
$diff[$k] = $v;
}
}
}
return $diff;
}
要比较的数组和第二个参数要比较的数组,并且将返回一个数组,其中包含要比较的数组中不存在于任何其他数组中的条目
$arr1 = array('first', 'second', 'third');
$arr2 = array('first', 'second', 'third', 'fourth', 'fifth');
print_r(array_diff($arr2, $arr1)); //Array ( [3] => fourth [4] => fifth )
但是如果你改变数组位置
$arr1 = array('first', 'second', 'third');
$arr2 = array('first', 'second', 'third', 'fourth', 'fifth');
print_r(array_diff($arr1, $arr2)); //Array ( )
if (empty(array_diff_key($arr, $sample) ) ) {
echo "they have the same key";
}
虽然我应该提到
55
与
"55"
相同,但这仅适用于整数的数组键