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 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c