[英]How i can Find Difference between two Associative arrays having one common Key
I am Working in Magento 2.3 i have two arrays 我在Magento 2.3中工作,我有两个数组
First Array: 第一个数组:
Array
(
[0] => Array
(
[name] => /l/u/luma-foam-roller.jpg
[image_id] => luma-foam-roller.jpg
)
[1] => Array
(
[name] => /l/u/luma-yoga-strap-set.jpg
[image_id] => luma-yoga-strap-set.jpg
)
[2] => Array
(
[name] => /m/b/mb04-black-0.jpg
[image_id] => mb04-black-0.jpg
)
[3] => Array
(
[name] => /l/u/luma-stability-ball-pink.jpg
[image_id] => luma-stability-ball-pink.jpg
)
[4] => Array
(
[name] => /m/b/mb01-blue-0.jpg
[image_id] => mb01-blue-0.jpg
)
}
Second Array: 第二个数组:
Array
(
[0] => Array
(
[name] => /m/b/mb01-blue-0.jpg
)
[1] => Array
(
[name] => /m/b/mb04-black-0.jpg
)
[2] => Array
(
[name] => /m/b/mb04-black-0_alt1.jpg
)
[3] => Array
(
[name] => /m/b/mb03-black-0.jpg
)
[4] => Array
(
[name] => /m/b/mb03-black-0_alt1.jpg
)
}
i want to find difference on the basis of name Expected Result for me is 我想根据名称的不同找到期望的结果对我来说是
Array
(
[0] => Array
(
[name] => /l/u/luma-foam-roller.jpg
[image_id] => luma-foam-roller.jpg
)
[1] => Array
(
[name] => /l/u/luma-yoga-strap-set.jpg
[image_id] => luma-yoga-strap-set.jpg
)
[3] => Array
(
[name] => /l/u/luma-stability-ball-pink.jpg
[image_id] => luma-stability-ball-pink.jpg
)
}
i tried Following Functions But Non of them are working for me 我尝试了以下功能,但没有一个对我有用
but not getting any success 但没有成功
I can't think of any one liner function that does this automatically at this time, but one straightforward way is just to use a loop. 我想不出有一个班轮函数可以自动执行此操作,但是一种简单的方法就是使用循环。
$names = array_column($second, 'name');
$diff = array();
foreach ($first as $k => $values) {
if (!in_array($values['name'], $names)) {
$diff[$k] = $values;
}
}
// print_r($diff);
Basically you just get all the names first (via array_column
) and make em flat, so that you can utilize in_array
and make your search and comparison. 基本上,您只需要首先获取所有名称(通过
array_column
)并使它们平坦即可,这样您就可以利用in_array
进行搜索和比较。
Then, it's just a humble foreach
and if
at that point. 然后,这只是一个不起眼的
foreach
, if
在那时。 This example creates a new copy of the difference. 本示例创建差异的新副本。 If you prefer not to create another copy, you can just
unset()
the first array and reverse the condition, leaving only the difference on the original. 如果您不想创建另一个副本,则可以只对第一个数组进行
unset()
并反转条件,只保留原始副本中的区别。
array_udiff can help: array_udiff可以帮助:
function compare_by_name($a, $b) {
$nameA = isset($a['name']) ? $a['name'] : '';
$nameB = isset($b['name']) ? $b['name'] : '';
return strcmp($nameA, $nameB);
}
print_r(array_udiff($arr1, $arr2, 'compare_by_name'));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.