将多个数组放在一个大的关联数组中 [英] Put multiple arrays in one large associative array

查看:140
本文介绍了将多个数组放在一个大的关联数组中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下循环创建一组数组:

I am creating a set of arrays with the following loop:

$assessmentArr = explode("&", $assessmentData);

foreach($assessmentArr as $data) {
    $fullArr = explode("_", $data);

    // Break down to only archetype and value
    $resultArr = explode("=", $fullArr[2]);

    //print_r($resultArr);
}

哪个会产生以下结果:

Array
(
    [0] => community-support
    [1] => 24
)
Array
(
    [0] => money-rewards
    [1] => 30
)
Array
(
    [0] => status-stability
    [1] => 15
)
Array
(
    [0] => personal-professional-development
    [1] => 32
)
Array
(
    [0] => community-support
    [1] => 9
)
Array
(
    [0] => money-rewards
    [1] => 12
)
Array
(
    [0] => status-stability
    [1] => 16
)
Array
(
    [0] => personal-professional-development
    [1] => 29
)

我需要将它们组合成一个数组,在[0]值匹配的地方,我需要将[1]值加在一起.

I need to combine these into one array, and where the [0] value matches, I need to add the [1] value together.

所以我希望最终输出为:

So I would like the final output to be something like:

Array
(
    [community-support] => 33
    [money-rewards] => 42
    [status-stability] => 31
    [personal-professional-development] => 61
)

我发现了以下问题:如何合并两个通过对合并后的值求和来创建数组,这将有助于我将这些值合并在一起,但是当数组未分配给变量时,我不确定该如何处理.我正在尝试做的事情是可行的还是我走错路了?

I found this question: How to merge two arrays by summing the merged values which will assist me in merging and adding the values together, but I'm not sure how to go about it when the arrays aren't assigned to a variable. Is what I am trying to do possible or am I going about this the wrong way?

推荐答案

不要让它变得复杂,只需检查一下结果数组是否已经具有带有该键的元素,如果没有初始化就添加它.例如

Don't make it complicated, just check if the results array already has an element with that key and if not initialize it otherwise add it. E.g.

(在循环中添加此代码):

(Add this code in your loop):

if(!isset($result[$resultArr[0]]))
    $result[$resultArr[0]] = $resultArr[1];
else
    $result[$resultArr[0]] += $resultArr[1];

然后您拥有所需的数组:

Then you have your desired array:

print_r($result);

这篇关于将多个数组放在一个大的关联数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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