矩阵和数组

时间:2018-05-05 08:53:21

标签: php

我有一个问题我完全无法解决这个问题。 你能救我吗?

我们有一个多变量数组,可以描述像Excel表格或矩阵等等。 第一个索引表示行和第二列。行可以有一个 不同数量的元素(列)。计算列中的金额并选择最高金额。

$a = [[1, 3, 4], [2, 5], [2 => 3, 5 => 8], [1, 1, 5 => 1]];

1 个答案:

答案 0 :(得分:0)

以下是一些符合您要求的代码:

$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];