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 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 itunes恢复数据最后一步发生错误
  • ¥15 关于#windows#的问题:2024年5月15日的win11更新后资源管理器没有地址栏了顶部的地址栏和文件搜索都消失了
  • ¥100 H5网页如何调用微信扫一扫功能?
  • ¥15 讲解电路图,付费求解
  • ¥15 有偿请教计算电磁学的问题涉及到空间中时域UTD和FDTD算法结合的
  • ¥15 three.js添加后处理以后模型锯齿化严重