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 怎么把多于硬盘空间放到根目录下
  • ¥15 Matlab问题解答有两个问题
  • ¥50 Oracle Kubernetes服务器集群主节点无法访问,工作节点可以访问
  • ¥15 LCD12864中文显示
  • ¥15 在使用CH341SER.EXE时不小心把所有驱动文件删除了怎么解决
  • ¥15 gsoap生成onvif框架
  • ¥15 有关sql server business intellige安装,包括SSDT、SSMS。
  • ¥15 stm32的can接口不能收发数据
  • ¥15 目标检测算法移植到arm开发板
  • ¥15 利用JD51设计温度报警系统