我正在尝试确定多维关联数组中每个数组的计数。例如,如果我有一个像这样的数组:
Array
(
[food] => Array
(
[soup] => Array
(
[chicken noodle] =>
[tomato] =>
[french onion] =>
)
[salad] => Array
(
[house] =>
[ceasar] =>
)
)
[drink] => Array
(
[soda] => Array
(
[coke] =>
[sprite] =>
[dr pepper] =>
)
[alcoholic] => Array
(
[whiskey] => Array
(
[Jim Beam] =>
[Jameson] =>
[Bushmills] =>
)
[vodka] => Array
(
[Stolichnaya] =>
[Ketel One] =>
[Grey Goose] =>
[Belvedere] =>
)
[rum] => Array
(
[Captain Morgan] =>
[Bacardi] =>
)
)
)
)
不太清楚如何解释,所以我会尽力而为。我想找出数组中每个数组的计数。所以我期望从这个数组中得到的值看起来像:
Array
(
// total count of all arrays at "level 1" (i.e. food & drink)
[0] => 2
// total count of all arrays at "level 2" (i.e. soup, salad, soda, alcoholic)
[1] => 4
// total count of all arrays at "level 3" (i.e. chicken noodle, tomato, french onion, house, ceasar, coke, sprite, dr pepper, whiskey, vodka, rum)
[2] => 11
// total count of all arrays at "level 4" (i.e. Jim Beam, Jameson, Bushmills, Stolichnaya, Ketel One, Grey Goose, Belvedere, Captain Morgan, Bacardi)
[3] => 9
)
现在我知道我只对值使用索引键而不是值,如果数组是标准索引数组,则更容易获取这些值(我认为我使用的是正确的术语在这里,请随时纠正我——当然,重点是让我在这里理解——而不是让某人只是“给我一个答案”:))因为我可以循环遍历数组for($i = 0 $i < count($array); $i++)
并增加我的计数因此。我已经在 SO 中搜索过这样的问题,但没有找到,如果我错过了,请随时简单地指出它。谢谢!
解决方案!(阅读评论以了解对话流程)
class Test {
public function getCounts($data) {
$levels = array();
$counts = $this->calc($levels, 0, $data);
return $counts;
}
private function calc(&$levels, $current, $parent) {
if(!isset($levels[$current])) {
$levels[$current] = 0;
}
foreach($parent as $child) {
$levels[$current]++;
if(is_array($child)) {
$this->calc($levels, $current+1, $child);
}
}
return $levels;
}
}
$test = new Test();
$data['food']['soup']['chicken_noodle'] = '';
$data['food']['soup']['tomato'] = '';
$data['food']['soup']['french onion'] = '';
$data['food']['salad']['house'] = '';
$data['food']['salad']['ceasar'] = '';
$data['drink']['soda']['coke'] = '';
$data['drink']['soda']['sprite'] = '';
$data['drink']['soda']['dr pepper'] = '';
$data['drink']['alcoholic']['whiskey']['Jim Beam'] = '';
$data['drink']['alcoholic']['whiskey']['Jameson'] = '';
$data['drink']['alcoholic']['whiskey']['Bushmills'] = '';
$data['drink']['alcoholic']['vodka']['Stolichnaya'] = '';
$data['drink']['alcoholic']['vodka']['Ketel One'] = '';
$data['drink']['alcoholic']['vodka']['Grey Goose'] = '';
$data['drink']['alcoholic']['vodka']['Belvedere'] = '';
$data['drink']['alcoholic']['rum']['Captain Morgan'] = '';
$data['drink']['alcoholic']['rum']['Bacardi'] = '';
$counts = $test->getCounts($data);
echo '<pre>';
print_r($counts);
exit('</pre>');
// Prints the following
// Array
// (
// [0] => 2
// [1] => 4
// [2] => 11
// [3] => 9
// )