0

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
  • 3
    Can you post some code which you have tried? The documentation of [`foreach(){}`](http://php.net/manual/en/control-structures.foreach.php) has extensive documentation on the topic and the tutorials available on the internet are endless. – MonkeyZeus Sep 14 '18 at 16:42

1 Answers1

1

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

Fabian
  • 67
  • 10
  • Thank you! I got the first part working. But what if I want to show the following: "Game 1 costs 24,99 " or "The game that costs 45,99 is called Game3" This has to happen outside of the foreach loop. But I have no clue how to make that work –  Sep 14 '18 at 16:58
  • @RainierLaan Test the condition in the loop, and assign the array key to a variable that you use when the loop is done. – Barmar Sep 14 '18 at 17:11
  • @RainierLaan This is different and depends on what exactly you want to do. You could do a array search and search for the game that costs 45,99, or you could select one specific game by name (e.g. `$spellen['Game 1'];` ) and then get all the values of it. Look at this answer [https://stackoverflow.com/a/6661561/9899193](https://stackoverflow.com/a/6661561/9899193) – Fabian Sep 14 '18 at 17:17
  • @RainierLaan Where does `45,99` come from, why is that the one you want to print at the end? – Barmar Sep 14 '18 at 18:26