douxun4173 2018-05-05 08:53 采纳率: 0%
浏览 46
已采纳

矩阵和数组

I have a problem I can not solve this task at all. can you help me.

We have a multivariate array that describes something like an Excel table or matrix, ect. the first index represents the row and the second column. The rows can have a different number of elements (columns). Count the amounts in the columns and select the highest.

$a = [[1, 3, 4], [2, 5], [2 => 3, 5 => 8], [1, 1, 5 => 1]];
  • 写回答

1条回答 默认 最新

  • dpfz27768 2018-05-05 10:29
    关注

    Here's some code that does what you asked:

    $a = [[1, 3, 4], [2, 5], [2 => 3, 5 => 8], [1, 1, 5 => 1]];
    
    $columnValues = [];
    $lastColumn = 0;
    foreach($a as $row){
        foreach($row as $column => $value){
            if($column > $lastColumn)
                $lastColumn = $column;
    
            if(isset($columnValues[$column]))
                $columnValues[$column] += $value;
            else 
                $columnValues[$column] = $value;
        }
    }
    
    //if you want to include empty columns too:
    for($column = 0; $column <= $lastColumn; $column++){
        if(!isset($columnValues[$column]))
            $columnValues[$column] = 0;
    }
    
    //sorting the column values by index:
    ksort($columnValues);
    
    $highestValue =  max($columnValues);
    $highestValueColumns = array_keys($array, max($array)); //contains all columns that have the same highest value. If there's only one column with the highest value, you can access it with $highestValueColumns[0];
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮