Packy February 2016

PHP foreach loop accessing different parts of multidimensional array

I am still trying to understand how the php foreach loop works with accessing certain parts of it. I have an array setup like this:

$product = Array
(
    [SX- Light weight] => Array
        (
            [bronze] => 4
            [silver] => 5
            [gold] => 6
        )

    [SS- Light weight] => Array
        (
            [bronze] => 4
            [silver] => 5
            [gold] => 6
        )
)

I have a foreach loop set up like so:

foreach ($product as  $name => $value) {
        # code...
        echo '<option value="'.$name.'">'.$name.'</option>'; 

    }

That spits me out $name as "SX- Light weight" for instance. How would I access the [bronze] number 4?

Answers


mkaatman February 2016

Reference it from the value.

foreach ($product as  $name => $value) {
    echo $value['bronze']; 
}


Frosty Z February 2016

foreach ($product as $name => $value) {
    // display 'bronze' index's value (assuming it is defined)
    echo 'For product '.$name.', bronze value = '.$value['bronze'];
}

You may want as well to display all the "metals" using a sub-loop:

foreach ($product as $name => $value)
{
  echo "For product ".$name.", values are: \n";

  // assuming $value is an associative array
  foreach ($value as $metal => $number)
  {
    echo "- ".$metal.": ".$number."\n";
  }
}


Don't Panic February 2016

It may help your understanding to visualize this two-dimensional array in two dimensions, sort of like a spreadsheet.

                  [bronze][silver][gold]
[SX- Light weight]   4       5       6
[SS- Light weight]   4       5       6

The foreach loops over the rows. This means that in

foreach ($product as  $name => $value) {

the $value is not a single value, it is a row, an array containing the values of the bronze, silver, and gold columns. So in the first iteration of this loop, for example, $value will contain

array('bronze' => 4, 'silver' => 5, 'gold' => 6)

You can iterate over each column in the row and do something with those values by using another foreach, but if you just need to access a specific column, you can use its key to specify which one you want, like this:

echo $value['bronze'];

Thinking of the contents of a two-dimensional array as rows and columns is a pretty common visualization. In fact, in PHP 5.5+ there is the array_column function, that allows you to pull all of the values from a specific column into a new array.

$bronze = array_column($product, 'bronze');  // for example.

Obviously if the array goes beyond two dimensions, this visualization becomes less useful.

Post Status

Asked in February 2016
Viewed 1,411 times
Voted 13
Answered 3 times

Search




Leave an answer