我有一个关联数组:
$input = [
['key'=>'x', 'value'=>'a'],
['key'=>'x', 'value'=>'b'],
['key'=>'x', 'value'=>'c'],
['key'=>'y', 'value'=>'d'],
['key'=>'y', 'value'=>'e'],
['key'=>'z', 'value'=>'f'],
['key'=>'m', 'value'=>'n'],
];
Run Code Online (Sandbox Code Playgroud)
我想简单地改革它:
$output = [
'x'=>['a','b','c'],
'y'=>['d','e'],
'z'=>'f',
'm'=>'n'
]
Run Code Online (Sandbox Code Playgroud)
所以基本上,条件是:
1. If same key found then put values in an array.
2. If no same key found then value remains string.
Run Code Online (Sandbox Code Playgroud)
如果您对对象更熟悉,可以用对象替换关联数组.
这是我解决此问题的解决方案:
foreach($input as $in){
if(!empty($output[$in['key']])){
if(is_array($output[$in['key']])){
$output[$in['key']][] = $in['value'];
continue;
}
$output[$in['key']] = [$output[$in['key']],$in['value']];
continue;
}
$output[$in['key']] = $in['value'];
}
print_r($output);
Run Code Online (Sandbox Code Playgroud)
但是我相信它可以以非常紧凑和有效的方式完成.如果有人有更好的解决方案,请评论您的答案 非常感谢您的帮助!
将数组重新格式化为[[x => a],[x => b],..]并合并所有子数组
$input = array_map(function($x) { return [$x['key'] => $x['value']]; }, $input);
$input = array_merge_recursive(...$input);
print_r($input);
Run Code Online (Sandbox Code Playgroud)