多次元連想配列内の各配列の数を決定しようとしています。たとえば、次のような配列がある場合:
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
// )