我试图用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很新颖。
'array_flip'会为你做 –
你能给你想要什么结果的例子看起来像? – Phil
我的原始目标(使$'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