我有一个这样的数组:
$array1 = [
['State'=>'Utah', 'users'=>5],
['State'=>'California', 'users'=>10]
]
$array2 = [
['State'=>'Utah', 'emails'=>18],
['State'=>'Arizona', 'emails'=>32],
['State'=>'California', 'emails'=>28],
]
我如何合并它们以便它会变成这样:
$mergedArray = [
['State'=>'Utah', 'users'=>5, 'emails'=>18],
['State'=>'Arizona', 'emails'=>32],
['State'=>'California', 'users'=>10, 'emails'=>28]
]
我尝试了array_merge,但它只保留了第一个数组的数据。
编辑:注意数组的长度和顺序如何不同。
答案 0 :(得分:2)
$array1 = ['Utah'=>['users'=>5],'California'=>['users'=>10]];
$array2 = ['Utah'=>['emails'=>18],'California'=>['emails'=>28]];
$result = array_replace_recursive($array1, $array2);
print_r($result);
输出:
Array
(
[Utah] => Array
(
[users] => 5
[emails] => 18
)
[California] => Array
(
[users] => 10
[emails] => 28
)
)
<强>更新强>
虽然您已更改了初始要求,但我也为 新 输入数据提供了解决方案。
使用过的功能:array_merge
和array_values
< / p>
// user data
$array1 = [
['State'=>'Utah', 'users'=>5],
['State'=>'California', 'users'=>10]
];
// email data
$array2 = [
['State'=>'Utah', 'emails'=>18],
['State'=>'Arizona', 'emails'=>32],
['State'=>'California', 'emails'=>28],
];
$result = [];
foreach (array_merge($array1, $array2) as $item) {
if (isset($result[$item['State']])) {
$result[$item['State']] = array_merge($result[$item['State']], $item);
} else {
$result[$item['State']] = $item;
}
}
$result = array_values($result);
print_r($result);
输出:
Array
(
[0] => Array
(
[State] => Utah
[users] => 5
[emails] => 18
)
[1] => Array
(
[State] => California
[users] => 10
[emails] => 28
)
[2] => Array
(
[State] => Arizona
[emails] => 32
)
)