所以我的二维数组看起来像这样:
0 1 2 3 4 5 6 7
------------------
0| 0 0 0 0 0 0 0 0
1| 0 0 1 0 0 0 0 0 <-- Sum of this Row is 1
2| 0 0 0 0 0 0 0 0
3| 0 0 0 0 0 0 0 0
4| 0 0 0 0 0 0 0 0
5| 0 0 0 0 0 0 0 0
6| 0 0 0 0 0 0 0 0 <-- Sum of this diagonal row is also 1
7| 0 0 0 0 0 0 0 0
^ Sum of this column is also 1
现在我可以通过以下方式获得行的总和:
$sumRow = array_sum($board[1]); //Is equal to 1
但我无法弄清楚如何在不进行循环的情况下获得列或对角线的总和。我知道我需要使用循环来获得对角线的总和,但有没有办法获得没有循环的列的总和?还是尽可能高效?
$sumCol = array_sum($board[][2]); //Something like this
$sumDiag = ?
答案 0 :(得分:5)
试试array_column
(PHP&gt; = 5.5.0):
$sumCol = array_sum(array_column($board, 2));
对于对角线总和,请使用:
$subDiag = array_sum( array_map(function($row, $index){
return $row[$index];
}, $board, array_keys($board)) );
答案 1 :(得分:3)
如何获得行,列和对角线之和的示例。我们的想法是分割数组,如下例所示:
diagonal +1 diagonal -2 0 |0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 |0 1 0 0 0 0 0 _0_0_1_0_0_0 0 0 0 |0 0 0 0 0 0 0 0 0 0 0 0 0| 0 0 0 |0 0 0 0 0 0 0 0 0 0 0 0 0| 0 0 0 |0 0 0 0 0 0 0 0 0 0 0 0 0| 0 0 0 |0 0 0 0 0 0 0 0 0 0 0 0 0| 0 0 0 |0_0_0_0_0_0_0_ 0 0 0 0 0 0| 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0| 0 0
这种方式很容易通过简单的array_walk获得任何对角线的对角线和:
$row_sum = function( $array, $row ) {
return array_sum( $array[$row] );
};
$column_sum = function( $array, $column ) {
return array_reduce( $array, function( $r, $i ) use ( $column ) {
return $r += $i[$column];
});
};
/**
* @param int $diagonal ( positive and negative )
*/
$diagonal_sum = function( $array, $diagonal ) {
$slice = array_map( function($i) use ($diagonal) {
return $diagonal < 0 ? array_slice($i, 0, $diagonal) : array_slice($i, $diagonal);
}, $diagonal > 0 ? array_slice($array, 0, -$diagonal) : array_slice($array, abs($diagonal)));
array_walk( $slice, function( &$item, $key ) {
$item = $item[$key];
});
return array_sum( $slice );
};
$array = array_map( function() { return array_fill( 0, 8, 0 ); }, array_fill( 0, 8, 0 ) );
$array[1][2] = 1;
echo $row_sum( $array, 1 );
echo $column_sum( $array, 2 );
echo $diagonal_sum( $array, 1 );