3 回答
TA贡献1853条经验 获得超6个赞
$chunk = 4;
$arr = array('1', '1', '1', '1', '1', '1', '1', '0', '1', '0', '1', '0', '0', '0', '0', '1');
// Split your array in chunks
$chunks = array_chunk($arr, 4);
// Max counts for 1 and 0
$max1 = $max0 = 0;
foreach ($chunks as $chunk) {
// count number of occurences of 1 and 0
$countedValues = array_count_values($chunk);
$cur1 = isset($countedValues[1]) ? $countedValues[1] : 0;
$cur0 = isset($countedValues[0]) ? $countedValues[0] : 0;
echo 'count 1 is ' . $cur1 . PHP_EOL;
echo 'count 0 is ' . $cur0 . PHP_EOL;
$max1 = max($max1, $cur1);
$max0 = max($max0, $cur0);
}
echo '1 max count is ' . $max1 . PHP_EOL . '0 max count is ' . $max0;
TA贡献1880条经验 获得超4个赞
简短的代码段可帮助您获得结果。
$i = 0;
foreach($result as $k => $v){
$temp[$k] = count(array_filter(array_column($result,$i)));
$i++;
}
在上面的代码中,array_column将从索引为0,索引为1等的所有数组中获取数据。
array_filter将删除0个值(默认性质)。
下面的输出包括所有垂直第1个的计数。
输出
Array
(
[0] => 4
[1] => 3
[2] => 2
[3] => 1
)
TA贡献1830条经验 获得超3个赞
您可以按如下所示对列1进行0计数并通过修改最后一个foreach循环进行计数
$columns = array();
foreach($result as $row){
foreach($row as $key => $val){
$columns[$key][] = $val;
if($val == "1"){
$new++;
}
else{
$exist++;
}
echo $val;
}
echo '<br/>';
}
$cols = array_map(function($v){
$temp = array_count_values($v);
return 'Element :'.array_keys($temp, max($temp))[0].' came '.max($temp).' times.';
}, $columns);
echo '<pre>';
print_r($cols);
结果
Array
(
[0] => Element :1 came 4 times.
[1] => Element :1 came 3 times.
[2] => Element :1 came 2 times.
[3] => Element :0 came 3 times.
)
- 3 回答
- 0 关注
- 171 浏览
添加回答
举报