2017-05-04 58 views
0

我试图用foreach循环中的变量$numberOfFoods更新每个键在关联数组中保存的元素数。这里是我的代码:如何计算每个键在PHP中的关联数组中保留的元素数?

$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很新颖。

+0

'array_flip'会为你做 –

+0

你能给你想要什么结果的例子看起来像? – Phil

+0

我的原始目标(使$'numberOfFoods = count(array_values($ countryAssocFood));'的建议符合我的原始目标,这将改变$ foodsArray = array(''''Souffle','Baguette' ,'Fois gras'], 'England'=> ['Bangers and mash','Tea and biscuits'], 'America'=> ['Hamburger','Steak and Eggs','Texas chili']' into'$ countriesByCuisine = array('Souffle'=>'France','Baguette'=>'France');'等等''以前的所有值'$ foodsArray'。 – theotheransel

回答

0

@Robbie Averill约为array_flip,以实现翻转键和值的“总体目标”。

有多种,更有效,方法来解决当前的代码,最好的一个很可能是array_map,但我也想向您提供为什么你当前的代码失败:

的问题是,你是计数$foodsArray每次迭代(它总是等于3),而不是计数$countryAssocFood

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

+0

他已经知道关于计数的问题 – Chinito

+0

这就是而不是我们从他解释问题的方式中所理解的,他首先说出他想做什么(用每个键所保存的元素数量更新foreach循环中的变量$ numberOfFoods),然后显示代码,然后说目前的(这个代码只是设置$ numberOfFoods变量e到整数3)。 在我看来,固定计数是他想要的。如果不是,他总是可以忽略我的答案。 – Growiel

+1

:D我们不要他想要的 – Chinito

相关问题