PHP中的分组和合并数组 [英] Grouping and Merging array in PHP

查看:186
本文介绍了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.

这篇关于PHP中的分组和合并数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆