dsgixl5195 2019-05-16 15:07
浏览 86
已采纳

PHP:聚合数组[重复]

This question already has an answer here:

Assuming I have the following 3 PHP arrays:

$arr1 = [1,2,3,4]
$arr2 = [5,2,4,1]
$arr3 = [2,1,2,2]

What's the most efficient built-in way that PHP has to add these arrays to elements in the same index of each array. Meaning, the final output would be the following:

$final = [8,5,9,7]

There should be an easier way than doing final = [$arr1[0]+$arr2[0]+$arr3[0]..] etc. Also, I need to assume there's a variable amount of arrays, so hard coding the math like above isn't correct.

</div>
  • 写回答

2条回答 默认 最新

  • doushi9376 2019-05-16 15:12
    关注

    Make them all one array and use array_sum and array_column

    $arr1 = [1,2,3,4];
    $arr2 = [5,2,4,1];
    $arr3 = [2,1,2,2];
    
    $all = [$arr1, $arr2, $arr3];
    
    foreach($all[0] as $key => $v){
        $result[$key] = array_sum(array_column($all, $key));
    }
    
    var_dump($result);
    

    Output:

    array(4) {
      [0]=>
      int(8)
      [1]=>
      int(5)
      [2]=>
      int(9)
      [3]=>
      int(7)
    }
    

    https://3v4l.org/qndQH

    This method will only work if all arrays are same length or the first is the longest.


    If you have an unknown amount of arrays within an name range then you can loop and use isset to see if the array exist, if yes add it to $all.

    $arr1 = [1,2,3,4,5];
    $arr2 = [5,2,4,1];
    $arr3 = [2,1,2,2];
    $arr4 = [2,1,2,2];
    $all = [];
    
    $i=1;
    while(isset(${"arr" . $i})){
        $all[] = ${"arr" . $i};
        $i++;
    }
    
    foreach($all[0] as $key => $v){
        $result[$key] = array_sum(array_column($all, $key));
    }
    
    var_dump($result);
    


    If you want it all super dynamic then you can use the code above and add what subarray is the longest and loop that in the last loop.

    $arr1 = [1,2,3,4,5];
    $arr2 = [5,2,4,1];
    $arr3 = [2,1,2,2];
    $arr4 = [2,1,2,2];
    $arr5 = [2,1,2,2,6,1,3,2];
    $all = [];
    
    // Add all subarrays dynamically and see which is the longest
    $i=1;
    $count = Null;
    while(isset(${"arr" . $i})){
        $all[] = ${"arr" . $i};
        if(count(${"arr" . $i}) > $count){
            $count = count(${"arr" . $i});
            $longkey = $i-1;
        }
        $i++;
    }
    
    // Loop the longest subarray
    foreach($all[$longkey] as $key => $v){
        $result[$key] = array_sum(array_column($all, $key));
    }
    
    var_dump($result);
    

    Working example:
    https://3v4l.org/lIVGo

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 求螺旋焊缝的图像处理
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 itunes恢复数据最后一步发生错误
  • ¥15 关于#windows#的问题:2024年5月15日的win11更新后资源管理器没有地址栏了顶部的地址栏和文件搜索都消失了
  • ¥100 H5网页如何调用微信扫一扫功能?