I have been trying to count the leaf node elements in a array. I'm thinking along the lines of:
array_walk_recursive()
.array_count_values()
.I'm unsure how to get a simple list array from array_walk_recursive()
, I just get a long string of values. Or is there a better way of achieving this result?
DESIRED RESULT:
flammable = 1
irritant = 2
toxic = 3
PHP:
$testArray = [
[
0 => 'toxic',
1 => 'irritant',
3 => 'flammable',
],
[
0 => 'toxic',
1 => 'irritant',
],
[
0 => 'toxic',
]
];
array_walk_recursive($testArray, function(&$value)
{
echo 'string = '.$value;
print_r(newArray); //How can i get this new array list?
});
$counts = array_count_values($newArray); //and use this to count values?
Try this, the numbers should show up in the $groups
array.
$groups = array();
array_walk_recursive($testArray, function(&$value) use (&$groups)
{
if (isset($groups[$value])) {
$groups[$value]++;
} else {
$groups[$value] = 1;
}
});
print_r($groups);