PHP Recursive Loop Multidimensional JSON Arrays | GeoJSON

How to Iterate JSON Arrays in PHP Using a Recursive Function with GeoJSON

Load and set your GeoJSON content into a PHP variable

Use json_decode to convert the JSON content into a php multidimensional array

Create a custom recursive function to iterate the JSON content

Run a while loop inside the custom function and call itself when it has children

Run a foreach loop on your root array from your geojson content

Create a new RecursiveArrayIterator class inside the loop

Call your custom recursive function and pass in your RecursiveArrayIterator class

Continue working and processing your GeoJSON array

Code Snippet: Preferred Method to Loop Through a Multidimensional JSON Array using recursion and a foreach loop with PHP & GeoJSON

//Fetches the GeoJSON array.
$geojson = file_get_contents("sampleGeoJSON.json",false);
 
//Converts GeoJSON into an associative array.
$geojson_array = json_decode($geojson,true);


//A recursive function to traverse the GeoJSON array.
function traverseGeoJSON($iterator) {
    
    //If there is a property left.
    while ( $iterator -> valid() ) {

        if($iterator->hasChildren()) 
            traverseGeoJSON($iterator -> getChildren());

        elseif($iterator->key() === "name")
            echo $iterator->current().PHP_EOL;
 
        //Jump to next property.
        $iterator -> next();
        
    } 
}

foreach($geojson_array as $location)
{
    //Defines iterator for each location.
    $iterator = new RecursiveArrayIterator($location);
    //Call traversestructure to parse the GeoJSON.
    traverseGeoJSON($iterator);
}

/*
OUTPUT
fortune island
Dinagat Islands
*/

That’s not all. The article also includes other ways to do the intended job and also an example of PHP GeoJSON. Stay tuned to learn more.

GeoJSON Multidimensional Array in PHP

GeoJSON is a JSON format for specifying geographical features and their non-spatial attributes. There are loads of attributes like coordinates, shapes, and geometries. GeoJSON is an essential data structure for many GIS-based applications.

GeoJSON is an extension of normal JSON

Despite the fact that they can be complex to interpret, at the end of the day they are an extension of JSON. So, we can loop through it in PHP using the same techniques we have already seen in the previous examples. Let’s see a sample GeoJSON.

{
{
  "type": "Feature",
  "geometry": {
    "type": "Point",
    "coordinates": [20, 10]
  },
  "properties": {
    "name": "fortune island"
  }
},
{
  "type": "Feature",
  "geometry": {
    "type": "Point",
    "coordinates": [125.6, 10.1]
  },
  "properties": {
    "name": "Dinagat Islands"
  }
}
}

This GeoJSON is rather simple and especially picked up for demonstration purposes. There we have a couple of locations and their coordinates. The desired end state should be as follows.

[LocationName]...

Basically, just the location names. So, that’s possible only if PHP could iterate the GeoJSON recursively and extract the desired form out of it.

PHP Recursive Loop through a Multidimensional Array

We recommend 2 steps to create a PHP recursive loop through a multidimensional array. First, create a custom function that can call itself for recursion. The function should accept a RecursiveArrayIterator class as its only parameter. Secondly, create a RecursiveArrayIterator with your json_decoded JSON array.

//Fetches the GeoJSON array.
$geojson = file_get_contents("sampleGeoJSON.json",false);
 
//Converts GeoJSON into an associative array.
$geojson_array = json_decode($geojson,true);


//A recursive function to traverse the GeoJSON array.
function traverseGeoJSON($iterator) {
    
    //If there is a property left.
    while ( $iterator -> valid() ) {

        if($iterator->hasChildren()) 
            traverseGeoJSON($iterator -> getChildren());

        elseif($iterator->key() === "name")
            echo $iterator->current().PHP_EOL;
 
        //Jump to next property.
        $iterator -> next();
        
    } 
}

foreach($geojson_array as $location)
{
    //Defines iterator for each location.
    $iterator = new RecursiveArrayIterator($location);
    //Call traversestructure to parse the GeoJSON.
    traverseGeoJSON($iterator);
}

/*
OUTPUT
fortune island
Dinagat Islands
*/

The GeoJSON file is fairly complex but with the right approach, we are able to extract the right piece of information.

Relevant Content: JSON with PHP

Related Reading on PHP Multidimensional Arrays

If you’re planning to be a developer, you’ll be working with JSON responses quite often. The reason is that most applications get data from the servers in the form of JSON, including the simple application we’ll see in this article.

That’s why looping through or parsing a JSON array with PHP is a common practice in development. In this article, we’ll see how to loop through a multidimensional JSON array with PHP. We will see a more complex way of looping through a multidimensional and explore why it is often recommended to take the difficult path.

More Multidimensional JSON Array PHP Loops Scenario

Background & Setup: Hotel Data in a Multidimensional JSON Array

We’ll develop a console-based application that parses a JSON array and prints out hotels’ information to the console. This application is simplistic but powerful enough to demonstrate the concept. You might find yourself coding an application that would parse a JSON response and display this information to a sophisticated hotel information web page at some point in your career.

Let’s assume that we have a JSON response with hotel information.

{
    "0" : {
        "HotelName" : "North Star Hotel",
        "HotelLocation" : "Northern City",
        "NearbyLocations":
        {
            "Airport": "Northern Airport",
    
            "Railway": "Northern Railway"
          
 
        },
        "RoomRate":
        {
            "PerNight": "120",
            "Tax": "15",
            "CurrencyCode": "USD"
 
        }
    },
 
 
    "1" : {
        "HotelName" : "South Star Hotel",
        "HotelLocation" : "Southern City",
        "NearbyLocations":
        {
            "Airport": "Southern Airport",
           
            "Railway": "Southern Railway"
            
 
        },
        "RoomRate":
        {
            "PerNight": "150",
            "Tax": "20",
            "CurrencyCode": "USD"
 
        }
    },
 
    "2" : {
        "HotelName" : "East Star Hotel",
        "HotelLocation" : "Eastern City",
        "NearbyLocations":
        {
            "Airport": "Eastern Airport",
          
            "Railway": "Eastern Railway"
            
 
        },
        "RoomRate":
        {
            "PerNight": "90",
            "Tax": "10",
            "CurrencyCode": "USD"
 
        }
    },
 
    "3" : {
        "HotelName" : "West Star Hotel",
        "HotelLocation" : "Western City",
        "NearbyLocations":
        {
            "Airport": "Western Airport",
 
            
            "Railway": "Western Railway"
            
 
        },
        "RoomRate":
        {
            "PerNight": "160",
            "Tax": "30",
            "CurrencyCode": "USD"
 
        }
    }
 
}

json array with PHP

json_decode your JSON multidimensional array into a PHP array

You should pass in a boolean value of true into json_decode when you want to decode a multidimensional array. The boolean flag tells the function that the output should be a function instead of a PHP StdClass. Arrays are the preferred output so there’s less chance to overwrite data.

The tree depth shows how complex a JSON is. In this case, the tree is just three levels deep. Since the JSON structure is simple, we can use nested foreach loops to iterate over the JSON array PHP. Let’s see how.

Option 1 – Loop Through a Multidimensional JSON array with PHP using Nested Loops

So, we’ll be using nested foreach loops to loop through the JSON array. But first things first, we will convert JSON into an array. We have already seen JSON to array conversion in one of our articles. Following the conversion, we will use nested foreach loops to dig into the JSON array PHP.

<?php
 
//Fetches the JSON object from a source.
$json = file_get_contents("hotels.json",false);
 
//Converts JSON object into an associative array.
$json_array = json_decode($json,true);
 
 
//First Loop - Loops through the hotels (0,1,2,3)
foreach($json_array as $id=>$hotel)
{
    //Second Loop - Loop through Hotel Properties (HotelName,HotelLocation,Nearby Locations, RoomRate)
    foreach($hotel as $key=>$value)
    {
        //Check if a property is an array. 
        if(is_array($value))
        {
            //Third loop - Loops properties that are arrays. They are said to nested/ have child nodes (Nearby Locations, RoomRate)
            foreach($value as $subkey=>$subvalue)
            {
                echo $subkey." : ".$subvalue."\n";
            }
        }
 
        else
        {
            echo $key." : ".$value."\n";
        }
 
        
    }
    echo "====================================\n";
}
 
?>

Here’s the output of the code.

HotelName : North Star Hotel        
HotelLocation : Northern City       
Airport : Northern Airport
Railway : Northern Railway
PerNight : 120
Tax : 15
CurrencyCode : USD
====================================
HotelName : South Star Hotel        
HotelLocation : Southern City       
Airport : Southern Airport
Railway : Southern Railway
PerNight : 150
Tax : 20
CurrencyCode : USD
====================================
HotelName : East Star Hotel
HotelLocation : Eastern City
Airport : Eastern Airport
Railway : Eastern Railway
PerNight : 90
Tax : 10
CurrencyCode : USD
====================================
HotelName : West Star Hotel
HotelLocation : Western City
Airport : Western Airport
Railway : Western Railway
PerNight : 160
Tax : 30
CurrencyCode : USD
====================================

We have looped through the JSON array and printed out hotels’ properties. You can use similar logic to get these properties and display them as you see fit. We’ve kept the display logic simple to emphasize more on the loops.

There are three nested loops to parse this JSON associative array. Suppose we had a JSON that was even more complex and had a depth of more than three levels. Now, you see where are we heading. The loop nesting will increase as the JSON gets more complex. 

The biggest concern with nested loops is that the code complexity increases. The complexity may not be apparent here, but it does affect the performance in a large-scale application. Secondly, the readability of the code suffers significantly as the nesting gets severe.

Fortunately, there is a robust solution to this problem. The solution is complicated, but it helps us overcome the concerns with nesting. We will see that next.

Option2 – Loop Through a Multidimensional JSON Array with PHP using RecurisveArrayIterator

The RecursiveArrayIterator is a special iterator by PHP. PHP describes it in the documentation, but it could be mind-boggling. So let’s put it in simple terms, RecursiveArrayIterator helps in looping through the arrays within arrays.

The array within arrays implies a parent-child relationship, and that’s why the documentation uses the terminologies pertaining to this relationship. Without further ado, let’s check out the code.

We will use the iterator’s functions to implement a logic that would help us traverse complex JSON structures robustly and efficiently. The descriptions of these functions can be seen in the documentation.

<?php
 
//Fetches the JSON object from a source.
$json = file_get_contents("hotels.json",false);
 
//Converts JSON object into an associative array.
$json_array = json_decode($json,true);
 
 
//A recursive function to traverse an array to any depth.
function traverseStructure($iterator) {
    
    //If there is a property left.
    while ( $iterator -> valid() ) {
 
        //If the property is an array or in other words, it has children.
        if ( $iterator -> hasChildren() ) {
       
            traverseStructure($iterator -> getChildren());
           
        }
        //If a property doesn't have children.
        else {
            
            echo $iterator -> key() . ' : ' . $iterator -> current() .PHP_EOL;   
        }
 
        //Jump to next property.
        $iterator -> next();
        
    }
   
    
}
 
//This loops through the hotels (0,1,2,3)
foreach($json_array as $hotel)
{
    //Defines iterator for each hotel.
    $iterator = new RecursiveArrayIterator($hotel);
    //Call traversestructure to parse the array to max depth
    traverseStructure($iterator);
    echo "==================================\n";
}
 
?>

Here’s the output.

HotelName : North Star Hotel      
HotelLocation : Northern City     
Airport : Northern Airport        
Railway : Northern Railway        
PerNight : 120
Tax : 15
CurrencyCode : USD
==================================
HotelName : South Star Hotel      
HotelLocation : Southern City     
Airport : Southern Airport
Railway : Southern Railway
PerNight : 150
Tax : 20
CurrencyCode : USD
==================================
HotelName : East Star Hotel
HotelLocation : Eastern City
Airport : Eastern Airport
Railway : Eastern Railway
PerNight : 90
Tax : 10
CurrencyCode : USD
==================================
HotelName : West Star Hotel
HotelLocation : Western City
Airport : Western Airport
Railway : Western Railway
PerNight : 160
Tax : 30
CurrencyCode : USD
==================================

The traverseStructure function uses RecursiveIterator’s function to loop through the array. The crucial thing in this function is recursion. The function calls itself if a property is an array or, in terms of the RecursiveIterator if it has children. 

Recursion is a concept in computer science. It works on the principle of “Divide and Conquer”, which means breaking a bigger problem into smaller problems and applying a common logic to these smaller problems. Definitely, it could be tricky for the starters, but practice makes a human perfect. There are numerous online resources for learning this amazing concept.

Note – Why RecursiveArrayIterator?

Recursion reduces the code complexity and increases performance. As we’ve already mentioned, the performance difference between the two methods may not be obvious here, but it would make a huge difference in a large-scale application.

Secondly, with this approach, it doesn’t matter what the JSON looks like. It could be many levels deeper, but the code is generic and robust enough to dig deep into the JSON array PHP

Conclusion

Wrap Up

That’s all for this article. We have seen two different approaches to looping through a multi dimensional JSON array. The first method, which uses a foreach loop, is dependent on JSON’s structure and could be inefficient when the nesting increases. The later method of using a RecursiveArrayIterator is efficient and robust.

Finally, the article features a section about GeoJSON in PHP. We hope you’ve learned some valuable concepts today. Stay tuned for more informative PHP articles. 

Classes and Functions Mentioned

file_get_contents: (PHP 4.3, 5, 7, 8) This is a built-in PHP function that is available from PHP 4.3 and has been included in the latest version of PHP. Given its utility and stability, the function is here to stay with no chance of depreciation anytime soon.

json_decode: (PHP 5.2+, 7, 8) This function is quite handy in transforming JSON to a PHP array or object. It is commonly used in various scenarios where transformation is necessary. Besides, it is a core function, and based on the extensive use over time it seems depreciation is unlikely in the near or distant future.

RecursiveArrayIterator: (PHP 5 >= 5.1.0, PHP 7, PHP 8) RecursiveArrayIterator is a built-in PHP class that provides appropriate methods for iterating over iterable data structures. This class has been a part of PHP from version 5 and made its way up to the latest version. Due to its stability, depreciation seems unlikely.

Want to explore further about PHP arrays?

We have many fun articles related to PHP arrays. You can explore these to learn more about arrays in PHP.

How to take form inputs and put them into a PHP associative array

How to put values in an associative array into another array in PHP

Tell if an element is present in an associative array PHP


Article Categories

Article Tags

© 2022 Confident.Systems