请考虑以下数组:
$reference = array(
'080604' => 4,
'080703' => 4,
'080734' => 2,
'080819' => 2,
'088341' => 2,
'805238' => 20,
'805283' => 4,
'805290' => 2,
'805849' => 2,
'806051' => 2,
'806068' => 2,
);
$test = array(
'080604' => 2,
'080703' => 4,
'080819' => 1,
'088341' => 2,
'805238' => 20,
'805283' => 4,
'805290' => 2,
'805849' => 2,
'806051' => 2,
'806068' => 2,
);
它们非常相似,但可以有一些不同,例如有可能:-$ reference的某些键根本不在$ test中-$ test的某些键根本不在$ reference中-所有键都存在,但是$ reference和$ test中的值不同(有时$ reference的值大于$ test,有时$ test的值大于$ reference)
我需要自动找出差异并以某种方式输出它们,不仅提供计数本身的差异,还提供描述,例如]
$result = [
'080604' => [
'reference' => 4,
'test' => 2
]
];
如果某些值仅在列表之一中:
$result = [
'1234567890' => [
'reference' => 0,
'test' => 2
]
];
或类似的东西。
有人有一个主意,这是以一种优雅的方式完成此工作的最佳方法吗?非常感谢!
迭代每个对象,并使用值填充数组:
$combined = [];
foreach ($reference as $key => $val) {
$combined[$key] = [
'test' => 0,
'reference' => $val,
];
}
foreach ($test as $key => $val) {
if (!isset($combined[$key])) {
$combined[$key] = [
'reference' => 0,
'test' => 0,
]
}
$combined[$key]['test'] = $val;
}
[$combined
将包含两个数组的两个值,并引用$reference
和$test
的两个元素。
尝试
$result = array_diff($reference, $test);
print_r($result)