如何计算PHP中关联数组中每个键所包含的元素数量?

时间:2017-05-04 03:16:15

标签: php arrays foreach associative-array

我正在尝试使用每个键在关联数组中保存的元素数来更新foreach循环中的变量$numberOfFoods。这是我的代码:

$foodsArray = array (
        'France' => ['Souffle' , 'Baguette' , 'Fois gras'],
        'England' => ['Bangers and mash' , 'Tea and biscuits'],
        'America' => ['Hamburger', 'Steak and Eggs', 'Texas chili']
    );
    $countriesByCuisine = array();       

    foreach ($foodsArray as $originCountry => $countryAssocFood) {
        $numberOfFoods = count(array_values($foodsArray));
        for ($countryAssocFoodIndex = 0; $countryAssocFoodIndex < $numberOfFoods; $countryAssocFoodIndex++) {
            $countriesByCuisine[$countryAssocFood[$countryAssocFoodIndex]] = $originCountry;
        }
    }

    foreach (array_keys($countriesByCuisine) as $foodFromCountry) {
        echo $foodFromCountry . ', From '  . $countriesByCuisine[$foodFromCountry] . '. ';
    }

实际上,此代码只是将$numberOfFoods变量设置为整数3,而不是更新数字以反映当前密钥保存的值的数量。我使用此代码的总体目标是学习如何转换数组,使值成为新数组中的键,这些键将其先前的键保存为值。请原谅我凌乱的代码,因为我对编程和PHP都很陌生。

1 个答案:

答案 0 :(得分:0)

@Robbie Averill正确地array_flip来实现你的目标&#34;总体目标&#34;翻转键和值。

有多种更有效的方法来修复当前代码,最好的方法可能是array_map,但我还想向您提供当前代码失败的原因:

问题在于,您为每次迭代计算$foodsArray(并且它总是等于3),而不是计算$countryAssocFood

$numberOfFoods = count(array_values($countryAssocFood));