【发布时间】:2017-05-04 03:16:15
【问题描述】:
我正在尝试使用每个键在关联数组中保存的元素数来更新 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 还很陌生。
【问题讨论】:
-
array_flip会为你做这些 -
你能举个例子说明你希望结果是什么样的吗?
-
标签: php arrays foreach associative-array