在PHP中两个关联数组的键上进行数组合并? [英] Array merge on key of two associative arrays in php?
本文介绍了在PHP中两个关联数组的键上进行数组合并?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何将这两个数组合并在一起?
How can I merge these two array together?
Array
(
[0] => Array
(
[id] => 5
[cnt] => 14
)
[1] => Array
(
[id] => 8
[cnt] => 2
)
)
Array
(
[0] => Array
(
[id] => 8
[binding] => hardcover
)
[1] => Array
(
[id] => 5
[binding] => softcover
)
)
预期结果是:
Array
(
[0] => Array
(
[id] => 5
[binding] => softcover
[cnt] => 14
)
[1] => Array
(
[id] => 8
[binding] => hardcover
[cnt] => 2
)
)
这两个数组的合并应该在[id]值上进行,而不是在任何类型的数组上进行.如何用php快速完成此操作?
The merge of these two array should happen on the [id] value and not on any sort of the array. How can I do this with php in a fast way?
推荐答案
$output = array();
$arrayAB = array_merge($arrayA, $arrayB);
foreach ( $arrayAB as $value ) {
$id = $value['id'];
if ( !isset($output[$id]) ) {
$output[$id] = array();
}
$output[$id] = array_merge($output[$id], $value);
}
var_dump($output);
(可选)如果您想重置输出的键,只需执行以下操作:
Optionally if you want to reset output's keys, just do:
$output = array_values($output);
这篇关于在PHP中两个关联数组的键上进行数组合并?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文