duanhuang1699 2015-06-03 19:49
浏览 53
已采纳

将多个数组放在一个大的关联数组中

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

Which produces the following results:

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
)

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?

  • 写回答

2条回答 默认 最新

  • dongliao9233 2015-06-03 19:52
    关注

    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);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化