我有一个像这样的数组
$chunk = 4;
$arr = array('1', '1', '1', '1', '1', '1', '1', '0', '1', '0', '1', '0', '0', '0', '0', '1');
我根据$chunk
将此数组修改为行和列。在此示例中,它将是 4x4 行和列。
我想做的是如何计算每列中有多少个“1”或“0”,并打印“1”或“0”的最大输出。
示例:
1110
1101
1110
1001
there are 4 number '1' in first column, so the output should be 4
我当前的代码:
function array_chunk_vertical($arr, $percolnum){
$n = count($arr);
$mod = $n % $percolnum;
$cols = floor($n / $percolnum);
$mod ? $cols++ : null ;
$re = array();
for($col = 0; $col < $cols; $col++){
for($row = 0; $row < $percolnum; $row++){
if($arr){
$re[$row][] = array_shift($arr);
}
}
}
return $re;
}
$result = array_chunk_vertical($arr, $chunk);
$new = 0;
$exist = 0;
foreach($result as $row){
foreach($row as $val){
if($val == "1"){
$new++;
}
else{
$exist++;
}
echo $val;
}
echo '<br/>';
}
最佳答案
非常短的片段可以帮助您获得结果。
$i = 0;
foreach($result as $k => $v){
$temp[$k] = count(array_filter(array_column($result,$i)));
$i++;
}
在上面的代码中,array_column将从第 0 个索引、第 1 个索引等的所有数组中获取数据。
array_filter将删除 0 个值(默认性质)。
下面的输出包含所有第一个垂直方向的计数。
输出
Array
(
[0] => 4
[1] => 3
[2] => 2
[3] => 1
)
关于php - 打印二维数组中每列的最大计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55762980/