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')));
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 />';
}
}
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:
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
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)));
How to count occurrence of values in multidimensional array in php
You can try to loop then check if year key and month key already exist
$group = [];
foreach ($array as $value) {
$month = $value[1][0];
if (!isset($group[$value[0]])) {
$group[$value[0]] = array('count' => 0);
}
if (!isset($group[$value[0]][$month])) {
$group[$value[0]][$month] = 0;
}
$group[$value[0]][$month] += 1;
$group[$value[0]]['count'] += 1;
}
print_r($group);
If you don't necessarily need the count, you can change the first if condition
's execution to $group[$value[0]] = array();
and the line $group[$value[0]]['count'] += 1;
foreach ($array as $value) {
$month = $value[1][0];
if (!isset($group[$value[0]])) {
$group[$value[0]] = array();
}
if (!isset($group[$value[0]][$month])) {
$group[$value[0]][$month] = 0;
}
$group[$value[0]][$month] += 1;
}
print_r($group);
PHP: Return count of some values in multidimensional array but retain other values i.e id
A properly constructed foreach loop will do the trick. When a name is first found, set it as a key, and declare a default subarray for it (id
and count
= 0
). Then just increment the count value for every occurrence.
Code: (Demo)
$array=[
['id'=>'6','name'=>'Adams Clasp'],
['id'=>185,'name'=>'Acrylic'],
['id'=>'268','name'=>'Adams Clasp (Splints)'],
['id'=>11,'name'=>'Arrow Clasp'],
['id'=>11,'name'=>'Arrow Clasp'],
['id'=>'0','name'=>'Labial Bow'],
['id'=>'6','name'=>'Adams Clasp'],
['id'=>'6','name'=>'Adams Clasp']
];
foreach($array as $a){
if(!isset($result[$a['name']])){
$result[$a['name']]=['id'=>$a['id'],'count'=>0];
}
++$result[$a['name']]['count'];
}
var_export($result);
Output:
array (
'Adams Clasp' =>
array (
'id' => '6',
'count' => 3,
),
'Acrylic' =>
array (
'id' => 185,
'count' => 1,
),
'Adams Clasp (Splints)' =>
array (
'id' => '268',
'count' => 1,
),
'Arrow Clasp' =>
array (
'id' => 11,
'count' => 2,
),
'Labial Bow' =>
array (
'id' => '0',
'count' => 1,
),
)
Related Topics
Create Programmatically a Variable Product and Two New Attributes in Woocommerce
Posting JSON Objects to Symfony 2
Best Way to Transfer an Array Between PHP and JavaScript
What Is the Most Efficient Way to Count All the Occurrences of a Specific Character in a PHP String
What Is a Factory Design Pattern in PHP
Run Composer with a PHP Script in Browser
How to Remove Blank Lines from Text in PHP
How to Insert Multiple Checkbox Values into a Table
How Get Value for Unchecked Checkbox in Checkbox Elements When Form Posted
How to Extract Query Parameters from a Url String in PHP
Php: Convert Milliseconds to Date
PHP Startup Unable to Load Dynamic Library PHP_Mongo.Dll
What's the Best Way to Pass a PHP Variable to JavaScript
Best Practices: Working with Long, Multiline Strings in PHP
Running Two PHP Versions on the Same Server