user5838715
user5838715

Reputation:

PHP - Display Multidimensional Associative array using foreach

I am trying to understand multidimensional associative arrays. I need to have a list of information using an associative array and displaying it with a foreach() loop.

The list goes like this:

enter image description here

I got to the point where I have an associative array containing all the information

 $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"
            ),
        );

But how can I display this information using a foreach() loop so my end result will look something like this:

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

Upvotes: 0

Views: 86

Answers (1)

Fabian
Fabian

Reputation: 177

This is very simple.

Example:

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'];
}

With foreach you loop through an array. The $gameName is the key, in your case "Game 1", and so on. The value is an array wicht contains all the values. You get them by $value['valuename'];

Upvotes: 1

Related Questions