PHP根据键将多个关联数组添加到新数组 [英] PHP Adding multiple associative arrays to new array based on key
本文介绍了PHP根据键将多个关联数组添加到新数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要基于该键合并一些关联数组。
这样:
I have a few associative arrays that I need to merge together based on there key. so:
array1:
[person1] => tony
[person2] => sandra
array2:
[person1] => london
[person2] => paris
需要是:
array 3
[person1] => tony , london
[person2] => sandra , paris
我遇到的问题是密钥可以是任何值,所以它可以是 person1,也可以是 hairyOtter,并且数组的大小可变。
The issue I'm having though is that the key could be any value , so it could be 'person1' or it could be 'hairyOtter' and the array is of varaible size.
推荐答案
假设每个对象都不是多维的
Assuming, that every is not multi-dimensional
$merged = array_merge_recursive($array1, $array2);
foreach ($merged as &$entry) {
if (is_array($entry)) {
$entry = implode(', ', $entry);
}
}
想法是, array_merge_recursive()
如果找到具有相同键的两个值,则创建一个新数组。其他一切保持不变。
The idea is, that array_merge_recursive()
creates a new array, if it find two values with the same key. Everything else stays untouched.
这篇关于PHP根据键将多个关联数组添加到新数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文