我正在尝试比较两个关联数组,并根据值和基于键获得差异。我尝试过使用带有闭包的array_filter
这两个数组是这样的:
数组1
$newArr = [
0 => [
'id' => 'UT5',
'qty' => '4'
],
1 => [
'id' => 'WRO',
'qty' => '3'
],
2 => [
'id' => 'SHO',
'qty' => '3'
]
];
数组2
$oldArr = [
0 => [
'id' => 'SHO',
'qty' => '1'
],
1 => [
'id' => 'UT5',
'qty' => '2'
],
];
我想要的输出如下:
array(3)
{
["UT5"]=> int(2)
["SHO"]=> int(2)
["WRO"]=> int(3)
}
我已经走到了这一步:
<?php
$newArr = [
0 => [
'id' => 'UT5',
'qty' => '4'
],
1 => [
'id' => 'WRO',
'qty' => '3'
],
2 => [
'id' => 'SHO',
'qty' => '3'
]
];
$oldArr = [
0 => [
'id' => 'SHO',
'qty' => '1'
],
1 => [
'id' => 'UT5',
'qty' => '2'
],
];
$toAdd = [];
foreach ($newArr as $item) {
$itemsToAdd = array_walk($oldArr, function ($k) use ($item, &$toAdd) {
if ($k['id'] == $item['id']) {
$toAdd[$k['id']] = max($k['qty'], $item['qty']) - min($k['qty'], $item['qty']);
}
});
}
var_dump($toAdd); die();
但是使用此功能,我当前的输出是:
array(2) {
["UT5"]=> int(2)
["SHO"]=> int(2)
}
请注意,缺少WRO。有没有办法可以添加条件来准确检查?我尝试了一些解决方案,例如!in_array,但是它们都没有给我所需的输出。
任何帮助表示赞赏!谢谢!
答案 0 :(得分:1)
这很简单,只有在两个数组中都存在密钥时,您的代码才会保存值。只需添加一个子句来检查旧数组中是否存在密钥DOESN&T。 (如果旧数组有一个没有新密钥的密钥,则也会相反)
if (!isset(old array [ new array key ]){
$newArray[new array key] = new array key and values;
您的程序结构针对计算机进行了优化,并且过于复杂而无法作为人类使用,我完全重写了它。
<?php
$newArr = [0 => ['id' => 'UT5', 'qty' => '4'], 1 => ['id' => 'WRO', 'qty' => '3'], 2 => ['id' => 'SHO', 'qty' => '3']];
$oldArr = [0 => ['id' => 'SHO', 'qty' => '1'], 1 => ['id' => 'UT5', 'qty' => '2'], ];
$newReset = [];
foreach( $newArr as $item ) {
$newReset[$item['id']] = $item['qty'];
}
$oldReset = [];
foreach( $oldArr as $item ) {
$oldReset[$item['id']] = $item['qty'];
}
foreach( $newReset as $key => $val ) {
if( isset( $oldReset[$key] ) ) {
$toAdd[$key] = max( $oldReset[$key], $val ) - min( $oldReset[$key], $val );
}
else $toAdd[$key] = intval($val);
}
var_dump( $toAdd );
这就是结果。
array(3) {
["UT5"]=>
int(2)
["WRO"]=>
int(3)
["SHO"]=>
int(2)
}
答案 1 :(得分:1)
一次通过
$toAdd = [];
foreach ($newArr as $item)
$toAdd[$item['id']] = $item['qty'];
foreach ($oldArr as $item)
if (isset($toAdd[$item['id']]))
$toAdd[$item['id']] = abs($toAdd[$item['id']] - $item['qty']);
else
$toAdd[$item['id']] = abs($item['qty']);
print_r($toAdd);