在PHP中分组和合并数组

时间:2014-11-21 09:39:50

标签: php arrays multidimensional-array grouping array-merge

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

$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
        )
    );

我希望结果的方式是if数组键的值" group"与键的名称相同"名称"应该合并。我想要下面提到的输出。

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

4 个答案:

答案 0 :(得分:0)

PHP函数array_reduce()的完美用法示例:

$array = array_values(
    array_reduce(
        $array,
        function (array $carry, array $item) {
            // Extract the group name into a variable for readability
            // and speed; it is used several times velow
            $key = $item['group'];
            // Initialize the group if it is the first entry in this group
            if (! array_key_exists($key, $carry)) {
                $carry[$key] = array(
                    'names' => array(),
                    'group' => $key,
                );
            }
            // Add the new names to the group in the output array
            $carry[$key]['names'] = array_merge($carry[$key]['names'], $item['names']);

            // Return the partial result
            return $carry;
        },
        array()
    )
);

代码使用array_reduce()迭代地构建一个包含期望值的新数组。

如果需要,回调函数会创建组,然后将处理过的项的名称合并到结果数组中的现有组中。

使用array_reduce()生成的数组按照它们在输入数组中出现的顺序使用group的值进行索引。对于已发布的数组,它们的键将为12。如果您不关心密钥,请取消对array_values()的调用,以便在速度和可读性方面获得一点改进。

函数array_values()删除键并返回一个使用从零开始的顺序数字键索引的数组(如问题中列出的那样)。

答案 1 :(得分:0)

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

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

代码:(Demo

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()从结果数组中删除临时关联键。

答案 2 :(得分:-1)

<?php
    //initialize our array
    $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
        )
    );
    //result will be here
    $result = array();

    foreach ($array as $key => $value) {
        //check if we have keys group or names to avoid errors
        if(!isset($value['group']) || !isset($value['names']))
            continue;

        //make a key in result array if its not exist
        if(!isset($result[$value['group']]))
        {
            $result[$value['group']] = $value['names'];
        }
        else
        {
            //add a values to key if it exists
            $result[$value['group']] = array_merge($result[$value['group']], 
                $value['names']);
            //filter same values
            $result[$value['group']] = array_values(array_unique($result[$value['group']]));
        }
    }
    print_r($result);

答案 3 :(得分:-1)

您可以迭代数组并将所有内容存储在一个单独的数组中。之后,您可以按照所需的格式创建输出数组,如下所示:

$groups = array();
foreach($array as $subArray) {
    if (!array_key_exists($subArray['group'], $groups)) {
        $groups[$subArray['group']] = array();
    }
    $groups[$subArray['group']] = array_merge($groups[$subArray['group']], $subArray['names']);
}

$result = array();
foreach($groups as $groupId => $group) {
    $result[] = array(
        'names' => $group,
        'group' => $groupId,
    );
}

print_r($result);