Counting elements inside a multidimensional associative array
So, I have the following data array in PHP
$array = array(
"animal" => "panda",
"location" => "San Diego",
"age" => "2",
),
array(
"animal" => "tiger",
"location" => "Bronx",
"age" => "5",
),
array(
"animal" => "panda",
"location" => "Bronx",
"age" => "3",
),
array(
"animal" => "tiger",
"location" => "bronx",
"age" => "3",
),
array(
"animal" => "panda",
"location" => "San Diego",
"age" => "2",
)
)
What I want to do is convert this to an associative array that will contain a counter for animals, places and age. so if I wanted to see how many pandas are in san diego and age 2, I would get access to the new array with $newArray['panda']['San Diego']['2'], and the output would be 2.
My problem is that I can easily run the loop and build an array and count the elements when it is completely static.
foreach($array as $a) {
$newArray[$a['animal']][$a['location']][$a['age']] += 1;
}
However, I want to know how to accomplish the same concept when the number of keys is dynamic. for example, what if in one call there is only a place and an animal, and sometimes in another call there can be a place, animal, age and gender.
, , , .
?
, . , , .
/**
* @param array $animals The whole animals array
* @param array $query Array containing keys and values you want to filter by
*
* @return array Animals that match $query
*/
function filterAnimals($animals, $query) {
return array_filter($animals, function ($animal) use ($query) {
// Check if $animal has every key and the corresponding value from $query
foreach ($query as $key => $value) {
if (!isset($animal[$key]) || $animal[$key] != $value) {
return false;
}
}
return true;
});
}
filterAnimals() $animals , $query. pandas - :
$result = filterAnimals($animals, [
'animal' => 'panda',
'location' => 'San Diego'
]);
, , $result:
$count = count($result);