按键值对数组进行分组 [英] Group array by keys value

查看:60
本文介绍了按键值对数组进行分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经四处搜索,但我无能为力,所以我会让这件事变得容易.这就是我在 print_r 中的内容:

I have searched around and I am at my wits end so I will make this easy. This is what I have in a print_r:

Array
(
    [0] => Array
        (
            [name] => client interaction
            [y] => 2.7
        )

    [1] => Array
        (
            [name] => client interaction
            [y] => 0.1
        )

    [2] => Array
        (
            [name] => project planning
            [y] => 0.1
        )

    [3] => Array
        (
            [name] => client interaction
            [y] => 5.9
        )

)

这就是我想要的:

Array
(
    [0] => Array
        (
            [name] => client interaction
            [y] => 8.7
        )

    [1] => Array
        (
            [name] => project planning
            [y] => 0.1
        )

)

推荐答案

您想要的数组是否绝对有必要使用数字 indeces?如果我要这样做,我会这样做(尽管与您想要的数组不同)

Is it absolutely necessary that your desired array use numeric indeces? If I were to do this I would do it this way (not the same as your desired array though)

$newArray = array();
foreach($array as $item)
{
  if(!isset($newArray[$item["name"]]))
    $newArray[$item["name"]] = 0;

  $newArray[$item["name"]] += $item["y"];
}

这会给你一个这种结构的数组:

This will give you an array of this structure:

Array
(
  [client interaction] => 8.7
  [project planning] => 0.1
)

要取回密钥,您只需使用 foreach 循环的第二种形式

To get the keys back you simply use the second form of the foreach loop

foreach($newArray as $name => $y)

$name 将包含原始数组中的 name$y y.

$name will contain the name and $y the y in your original array.

这篇关于按键值对数组进行分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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