PHP中的分组和合并数组

问题描述:

我有一个下面提到的数组.

I have an array mentioned below.

$array = array(
        '0' => array(
            'names' => array(0 => 'Apple'),
            'group' => 1
        ),
        '1' => array(
            'names' => array(0 => 'Mango'),
            'group' => 1
        ),
        '2' => array(
            'names' => array(0 => 'Grapes'),
            'group' => 1
        ),
        '3' => array(
            'names' => array(0 => 'Tomato'),
            'group' => 2
        ),
        '4' => array(
            'names' => array(0 => 'Potato'),
            'group' => 2
        )
    );

我想要这样的结果:如果数组键"group"的值相同,则应合并键"names"的值.我想要下面提到的输出.

I want the result in such a way that the if the value of the array key "group" is same then the values of the key "names" should be merged. I want the output mentioned below.

    $array = array(
        '0' => array(
            'names' => array(0 => 'Apple', 1 => 'Mango', 2 => 'Grapes'),
            'group' => 1
        ),
        '1' => array(
            'names' => array(0 => 'Tomato', 1 => 'Potato'),
            'group' => 2
        )
    );

只需将group值用作临时关联键,就可以快速确定(迭代时)是否应存储整行数据,或者仅存储将names值附加到现有子数组.

By simply using the group values as temporary associative keys, you can swiftly determine (while iterating) if you should store the whole row of data, or just append the names value to an existing subarray.

**如果您的项目数据可能包含具有多个names值的输入子数组,则应更新您的问题以阐明这种可能性. (边缘演示)(

*if your project data may contain input subarrays with more than one names value, you should update your question to clarify this possibility. (Fringe Demo) (Fringe Demo2)

代码:(演示)

foreach ($array as $row) {
    if (!isset($result[$row['group']])) {
        $result[$row['group']] = $row;
    } else {
        $result[$row['group']]['names'][] = $row['names'][0];
    }
}

var_export(array_values($result));

输出:

array (
  0 => 
  array (
    'names' => 
    array (
      0 => 'Apple',
      1 => 'Mango',
      2 => 'Grapes',
    ),
    'group' => 1,
  ),
  1 => 
  array (
    'names' => 
    array (
      0 => 'Tomato',
      1 => 'Potato',
    ),
    'group' => 2,
  ),
)

您可以使用array_values()从结果数组中删除临时关联键.

You can use array_values() to remove the temporary associative keys from the result array.