简体   繁体   中英

How to count array value per column?

I have an array like this

$chunk  = 4; 

$arr    = array('1', '1', '1', '1', '1', '1', '1', '0', '1', '0', '1', '0', '0', '0', '0', '1');

I modified this array into rows and columns based on the $chunk . In this example it would be a 4x4 rows and columns.

What I'd like to do is how to count how many '1' or '0' in every column and print the largest output from either '1' or '0'.

Example:

1110
1101
1110
1001

there are 4 number '1' in first column, so the output should be 4

My current code:

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/>';
}

Very short snippet to help you out with result.

$i = 0;
foreach($result as $k => $v){
    $temp[$k] = count(array_filter(array_column($result,$i)));
    $i++;
}

In above code, array_column will fetch data from all the arrays with 0th index, 1st index, and so on.
array_filter will remove 0 values(default nature).
Below output consist of count of all the 1st vertically.

Output

Array
(
    [0] => 4
    [1] => 3
    [2] => 2
    [3] => 1
)

Demo

You can count the column 1 and 0 counting by modifying your last foreach loop as follow

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

Result

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.
)

I've updated the chunk method to simplify it a bit and then from this result I use a combination of array_column() and array_sum() to add up the totals for each column. You then can use max() to find the highest (comments also in code)...

$chunk  = 4;
$arr    = array('1', '1', '1', '1', '1', '1', '1', '0', '1', '0', '1', '0', '0', '0', '0', '1');

function array_chunk_vertical($arr, $percolnum){
    $re = [];
    foreach ( $arr as $number => $value )   {
        // Use modulus % to put value in correct column
        $re [$number % $percolnum][] = $value;
    }
    return $re;
}
$result = array_chunk_vertical($arr, $chunk);

$count = [];
// Loop over first row of output
foreach($result[0]  as $column => $row){
    // Sum up the results of taking all the column values for this column
    $count[$column] = array_sum(array_column($result, $column));
}
// Extract highest
$highest = max($count);
// Find highest and output which one it is.
echo $highest ." in ". (array_search($highest, $count)+1);

results in

4 in 1
$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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM