Counting Values in Multidimensional Array

Counting Values in Multidimensional Array

This can be done with a simple iteration:

$counts = array();
foreach ($array as $key=>$subarr) {
// Add to the current group count if it exists
if (isset($counts[$subarr['group']]) {
$counts[$subarr['group']]++;
}
// or initialize to 1 if it doesn't exist
else $counts[$subarr['group']] = 1;

// Or the ternary one-liner version
// instead of the preceding if/else block
$counts[$subarr['group']] = isset($counts[$subarr['group']]) ? $counts[$subarr['group']]++ : 1;
}

Update for PHP 5.5

In PHP 5.5, which has added the array_column() function to aggregate an inner key from a 2D array, this can be simplified to:

$counts = array_count_values(array_flip(array_column($array, 'group')));

Counting Values in Multidimensional Array PHP

You can simply use array_count_values along with call_user_func_array like as

array_count_values(call_user_func_array('array_merge', $array));

PHP: Count and display the value of a multidimensional array

Simple enough here is an example:

<?php

/*Create the array for example */
$data[0]['city'] = "LONDON";
$data[0]['country'] = "ENGLAND";
$data[1]['city'] = "LONDON";
$data[1]['country'] = "ENGLAND";
$data[2]['city'] = "LONDON";
$data[2]['country'] = "ENGLAND";
$data[3]['city'] = "PARIS";
$data[3]['country'] = "FRANCE";
$data[4]['city'] = "LIVERPOOL";
$data[4]['country'] = "ENGLAND";
$data[5]['city'] = "ROME";
$data[5]['country'] = "ITALY";
$data[6]['city'] = "ROME";
$data[6]['country'] = "ITALY";
$data[7]['city'] = "PARIS";
$data[7]['country'] = "FRANCE";
$data[8]['city'] = "BRISTOL";
$data[8]['country'] = "ENGLAND";

/* print the array for show
echo '<pre>';
print_r($data);*/

foreach($data as $val){
if(!isset($newData[$val['country']][$val['city']])){
$newData[$val['country']][$val['city']] = 1;
} else {
++$newData[$val['country']][$val['city']];
}
$sorted["{$val['country']} - {$val['city']}"] = $newData[$val['country']][$val['city']];
}

/* print created array */
echo '<pre>';
print_r($newData);

/* print the sorted array */
arsort($sorted);
print_r($sorted);

Will return:

Array
(
[ENGLAND] => Array
(
[LONDON] => 3
[LIVERPOOL] => 1
[BRISTOL] => 1
)

[FRANCE] => Array
(
[PARIS] => 2
)

[ITALY] => Array
(
[ROME] => 2
)

)
Array
(
[ENGLAND - LONDON] => 3
[FRANCE - PARIS] => 2
[ITALY - ROME] => 2
[ENGLAND - LIVERPOOL] => 1
[ENGLAND - BRISTOL] => 1
)

Edit - Added select from $newData:

Example of select - just to illustrate how to loop and get your values and keys:

?><select id="city" name="city"><?php
foreach($newData as $country => $cities){

foreach($cities as $city => $quantity){
?>
<option id="<?php echo $city;?>" value='<?php echo "$country-$city";?>' ><?php echo $city;?></option>
<?php
}

}
?></select><?php

Will return:

Sample Image

Which is:

<select id="city" name="city">        
<option id="LONDON" value="ENGLAND-LONDON">LONDON</option>
<option id="LIVERPOOL" value="ENGLAND-LIVERPOOL">LIVERPOOL</option>
<option id="BRISTOL" value="ENGLAND-BRISTOL">BRISTOL</option>
<option id="PARIS" value="FRANCE-PARIS">PARIS</option>
<option id="ROME" value="ITALY-ROME">ROME</option>
</select>

Edit - if you want this: all data sorted and countries

Sample Image
Do this:

add

$sorted2[$val['city']] = $newData[$val['country']][$val['city']];
$countries[$val['city']] = $val['country'];

to the first foreach after $sorted...

after the loop add:

arsort($sorted2);

And in the select loop do this:

?><select id="city" name="city"><?php
foreach($sorted2 as $city => $quantity){
?>
<option id="<?php echo $city;?>" value='<?php echo $city;?>' ><?php echo "$city $countries[$city] ($quantity)";?></option>
<?php
}
?></select><?php

How to count all values in a multidimensional array?

Since your array is not flattened, you will need to visit each value and increment unless you want to call merging functions.

Code: (Demo)

$array = [
1 => [1, 12, 2],
2 => [1, 13, 3],
3 => [1, 12, 2],
4 => [1],
5 => [1]
];

// make the generated value available outside of function scope
// \-------------------------------v--------------------------/
array_walk_recursive($array, function($v)use(&$output) { // visit each leafnode
if (isset($output[$v])) { // check if the key has occurred before
++$output[$v]; // increment
} else {
$output[$v] = 1; // declare as 1 on first occurrence
}
});

var_export($output);

Output:

array (
1 => 5,
12 => 2,
2 => 2,
13 => 1,
3 => 1,
)

Or, non-recursively:

foreach ($array as $row) {
foreach ($row as $v) {
if (isset($output[$v])) { // check if the key has occurred before
++$output[$v]; // increment
} else {
$output[$v] = 1; // declare as 1 on first occurrence
}
}
}

Or, a functional one-liner to flatten then count:

var_export(array_count_values(array_reduce($array, 'array_merge', array())));

Or, a functional one-liner with the splat operator to flatten then count:

var_export(array_count_values(array_merge(...$array)));

Count specific values in multidimensional array

$number_of_green_fruit = 0;
for ($row = 0; $row < 3; $row++) {
if($fruit[$row]["color"]=="green") {
$number_of_green_fruit++;
echo $fruit[$row]["name"] . '<br />';
}
}

Multi-Dimensional array count in PHP

$count = 0;
foreach ($array as $type) {
$count+= count($type);
}

Getting count of elements in multidimensional array and specifying a filter

Count of country records:

$dataCountry = array_column($data, 'country');
echo "total: ", count($dataCountry);

Count of The Netherlands:

$dataCountryCount = array_count_values(array_filter($dataCountry));
echo $dataCountryCount['The Netherlands'] ?? 0;

Multiple search filter:

$filter = ['country' => 'The Netherlands', 'continent' => 'Europe'];
$dataFilter = array_filter($data, function($item) use ($filter) {
return $filter == array_intersect_key($item, $filter);
});
echo 'total:', count($dataFilter);

print_r($dataFilter);

Count string elements in an array in a multidimensional array

If you want to use filter, something like this should work with your struct:

var laptopTotal = playerStock.filter { $0.productName == "laptop" }.count


Related Topics



Leave a reply



Submit