PHP - Accessing Multidimensional Array Values

Solution 1:

The thing that is probably tripping you up is that suitability is an array of arrays not just an array so in an example where you want to get the species_name property of the first second top level element you would use something like

$array[1]["suitability"][0]["species_name"];

It's worth noting that your first array does not contain a "suitability" value so that would not be able to be accessed. In a foreach loop you could use a construct similar to this:

foreach($array as $value){
    if (isset($value["suitability"])){
        echo $value["suitability"][0]["species_name"];
    }
}

Solution 2:

You may take a look at PHP: RecursiveArrayIterator class

This allow you to iterate over multiples nested ArrayIterator. If you're not using any ArrayIterator, then you should consider to try them.

Solution 3:

Iracicot's answer helped me find my way towards accessing the values of a recursive array using the RecursiveIterator class as below. My solution ended up using the even more useful RecursiveIteratorIterator class as per http://php.net/manual/en/class.recursiveiteratoriterator.php. Please bear in the mind the very useful fact that the end product is a flattened array which I personally found much easier to work with.

<table style="border:2px;">
  <tr>
    <th>Time</th>
    <th>Service Number</th>
    <th>Destination</th>
  </tr>
<?php 
foreach($stops as $buses){
       $iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($buses));
       $bus = (iterator_to_array($iterator,true)); 
       print('<tr><td>'.$bus['AimedDepartureTime'].'</td><td>'.$bus['PublishedLineName'].'</td><td>'.$bus['DirectionName'].'</td></tr>');
}
?>
</table>

Solution 4:

For getting nested element value from multidimensional array (with optional fallback to default value) you can use get method from this array library:

Arr::get($array, "$index1.suitability.$index2.species_name")

// Or using array of keys
Arr::get($array, [$index1, 'suitability', $index2, 'species_name'])