我一直在尝试计算数组中的叶节点元素。 我的想法是:
array_walk_recursive()
。array_count_values()
。我不确定如何从
array_walk_recursive()
获取一个简单的列表数组,我只是得到一长串值。或者有更好的方法来达到这个结果吗?
期望的结果:
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?
试试这个,数字应该显示在
$groups
数组中。
$groups = array();
array_walk_recursive($testArray, function(&$value) use (&$groups)
{
if (isset($groups[$value])) {
$groups[$value]++;
} else {
$groups[$value] = 1;
}
});
print_r($groups);
您可以使用递归迭代器。 演示
$iterator = new RecursiveIteratorIterator(
new RecursiveArrayIterator($array)
);
$result = [];
foreach ($iterator as $leafNode) {
$result[$leafNode] = ($result[$leafNode] ?? 0) + 1;
}
array_walk_recursive()
演示
$result = [];
array_walk_recursive(
$array,
function ($leafNode) use (&$result) {
$result[$leafNode] = ($result[$leafNode] ?? 0) + 1;
}
);
var_export($result);
或者(最简单)因为您的数组正好有 2 个级别,并且第一个级别有数字键,您可以展平,然后对值进行计数。 演示
var_export(
array_count_values(
array_merge(...$array)
)
);