[英]How to combine/merge an multidimension array that has same keys in PHP?
So I have this array which the vardump looks like this: 因此,我有一个数组,其中vardump看起来像这样:
array (size=4)
0 =>
array (size=1)
'field_4' =>
array (size=1)
0 => string 'item-1' (length=6)
1 =>
array (size=1)
'field_4' =>
array (size=1)
0 => string 'info-1' (length=6)
2 =>
array (size=1)
'field_5' =>
array (size=1)
0 => string 'item-2' (length=6)
3 =>
array (size=1)
'field_5' =>
array (size=1)
0 => string 'info-2' (length=6)
So I am trying to combine the array with the same key for example 'field_4' would be merge/combined into an array that has 2 items "item-1" and "info-1". 因此,我尝试将具有相同键的数组组合在一起,例如,“ field_4”将被合并/合并为具有2个项“ item-1”和“ info-1”的数组。
So the end result I would like is this: 所以我想要的最终结果是:
array (size=2)
0 =>
array (size=1)
'field_4' =>
array (size=2)
0 => string 'item-1' (length=6)
1 => string 'info-1' (length=6)
1 =>
array (size=1)
'field_5' =>
array (size=1)
0 => string 'item-2' (length=6)
1 => string 'info-2' (lenght=6)
So is there a PHP convenience function to handle this or do I have to rebuild the array? 那么是否有PHP便利函数来处理此问题,还是我必须重建数组?
Thanks for looking. 感谢您的光临。
Just iterate over the input array, building the merged array: 只需遍历输入数组,构建合并数组:
$merged = array();
foreach ($input as $a)
foreach ($a as $k => $v)
foreach ($v as $v2)
$merged[$k][] = $v2;
And then flatten it into your weird required output: 然后将其展平为您需要的奇怪输出:
$flattened = array();
foreach ($merged as $k => $v)
$flattened[] = array($k => $v);
Input: 输入:
$input = array(
array('field_4' => array('item-1')),
array('field_4' => array('info-1')),
array('field_5' => array('item-2')),
array('field_5' => array('info-2')),
);
Output: 输出:
array(
array('field_4' => array('item-1', 'info-1')),
array('field_5' => array('item-2', 'info-2')),
)
When dumping output, print_r
or var_export
make for a much more readable example than var_dump
转储输出时, print_r
或var_export
示例比var_dump
可读得多
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.