PHP-使用foreach显示多维关联数组
我试图理解多维关联数组。我需要有一个使用关联数组的信息列表,并用foreach循环显示它 清单如下:PHP-使用foreach显示多维关联数组,php,arrays,Php,Arrays,我试图理解多维关联数组。我需要有一个使用关联数组的信息列表,并用foreach循环显示它 清单如下: Game 1 can be played with 10 to 20 players, The minimal age is 8+ and the game has a price of 24,99 Game 2 can be played with 2 to 24 players, The minimal age is 12+ and the game has a price of 34,9
Game 1 can be played with 10 to 20 players, The minimal age is 8+ and the game has a price of 24,99
Game 2 can be played with 2 to 24 players, The minimal age is 12+ and the game has a price of 34,99
Game 3 can be played with 6 to 8 players, The minimal age is 6+ and the game has a price of 45,99
Game 2 costs 24,99
The game that costs 45,99 is called Game 3
我得到了一个包含所有信息的关联数组
$spellen = array(
"Game1" => array (
"Amount of players" => "10 to 20",
"Age" => "8+",
"Price" => "€24,99"
),
"Game2" => array (
"Amount of players" => "2 to 24",
"Age" => "12+",
"Price" => "€34,99"
),
"Game3" => array (
"Amount of players" => "6 to 24",
"Age" => "6+",
"Price" => "€45,99"
),
);
但是如何使用foreach循环显示此信息,以便最终结果如下所示:
Game 1 can be played with 10 to 20 players, The minimal age is 8+ and the game has a price of 24,99
Game 2 can be played with 2 to 24 players, The minimal age is 12+ and the game has a price of 34,99
Game 3 can be played with 6 to 8 players, The minimal age is 6+ and the game has a price of 45,99
Game 2 costs 24,99
The game that costs 45,99 is called Game 3
这很简单
例如:
foreach($spellen as $gameName => $value) {
echo $gameName . "can be played with " . $value['Amount of players'] . " Players, the minimal age is " . $value['Age'] . "and the game has a price of " . $value['price'];
}
使用foreach可以循环遍历数组。$gameName是关键,在您的示例中是Game1,以此类推。该值是包含所有值的数组。您通过$value['valuename']获得它们 你能发布一些你试过的代码吗?的文档中有大量关于该主题的文档,而internet上提供的教程也数不胜数。谢谢!我让第一部分开始工作了。但是如果我想展示以下内容:游戏1花费24,99美元,或者游戏3花费45,99美元,这必须发生在foreach循环之外。但我不知道该怎么做work@RainierLaan测试循环中的条件,并将数组键指定给完成循环时使用的变量。@rainierralan这是不同的,取决于您到底想做什么。你可以做一个数组搜索,然后搜索花费45,99美元的游戏,或者你可以按名称选择一个特定的游戏,例如$spellen['game 1'];然后得到它的所有值。看看这个答案@rainierralan,45,99来自哪里,为什么你要在最后打印这个?