我试图在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的新手。
@robbie averill对array_flip
的正确目标是"总体目标"翻转键和值。
有多种修复您当前代码的方法,最好的方法可能是array_map
,但我也想为您提供当前代码失败的原因:
问题是您要计算每种迭代的$foodsArray
(并且总是等于3(,而不是计数$countryAssocFood
:
$numberOfFoods = count(array_values($countryAssocFood));