Recursive Loop Multidimensional JSON Arrays in PHP | GeoJSON

Last Updated on

CraftyTechie is reader-supported. When you buy through links on our site, we may earn an affiliate commission.

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

  1. Load and set your GeoJSON content into a PHP variable
  2. Use json_decode to convert the JSON content into a php multidimensional array
  3. Create a custom recursive function to iterate the JSON content
  4. Run a while loop inside the custom function and call itself when it has children
  5. Run a foreach loop on your root array from your geojson content
  6. Create a new RecursiveArrayIterator class inside the loop
  7. Call your custom recursive function and pass in your RecursiveArrayIterator class
  8. Continue working and processing your GeoJSON array

PHP Code Example: Loop Through a Multidimensional JSON Array using recursion and a foreach loop with 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

PHP Fundamentals Recommendations

This article is part of our content on PHP Fundamentals. It includes the core concepts that build upon the foundation of writing high-quality PHP code. If you are looking to grow your PHP development abilities. Check out the following recommended affiliate resources.

We do make a commission if you do choose to buy through our links. It is one of the ways that help support our mission here at FuelingPHP.

Book: Fundamentals of Web Development

This book is for you if you are starting to learn how to build websites. It is more than just an “intro to programming” book. You will learn the concepts and tips on what goes into creating a high-quality website. Today’s websites are more than text on a screen. They are highly complex applications that encourage user experience. Learn the fundamentals of good web development with this book.

Check it out on Amazon

Book: Programming in PHP (O’Reilly)

O’Reilly should not need any introduction. They are the top publishers when it comes to books on programming and technology. This book fits well within their vast library. If you are newer to the PHP language or want to keep a solid reference by your side. I highly recommend this book for your collection.

Check it out on Amazon

Book: Design Patterns in PHP

I highly recommend this book to any intermediate-level web developer. It takes the theories and best practices of writing high-quality code via design patterns and applies them to PHP. It is a great resource to take your career to the next level

Check it out on Amazon

Video Course: PHP Fundamentals (Pluralsight)

Want to quickly learn PHP? This PHP Fundamentals course is ideal for beginner PHP developers. It is a deep dive into the concepts, structures and well “fundamentals” of PHP development. It includes high-quality video & interactive resources that teach you really fast. I highly recommend this if you are getting started in your PHP journey.

Click here for a 10-day free trial to Pluralsight

Complete Learning Path: Web Development (Pluralsight)

You should definitely check out this learning path from Pluralsight. They have a huge list of video courses, training, and interactive lessons on growing your web development career. You get access to the full library of hundreds of resources for a single monthly subscription. It truly is like Netflix for your career.

Click here to see details (10-day free trial included)

Want more reviews? Check out our HUGE list of Beginner Web Development Books We’ve Researched and Reviewed for you.

Looping through Multidimensional Arrays in PHP

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.

Learn More About Loops in PHP

Want to learn how to use loops in PHP? This article is part of our series on looping through PHP arrays. Check out our full series to become a PHP array loop ninja.

Learn the Fundamentals of Good Web Development

Please take a moment and sign up for our free email course on the fundamentals of good web development. Every week is packed with a roundup of articles on our site and from around the web, where we go deep into developing exceptional web applications. We have meetups, code reviews, slack chats, and more.

Click here to get started

Did you find this article helpful?

Join the best weekly newsletter where I deliver content on building better web applications. I curate the best tips, strategies, news & resources to help you develop highly-scalable and results-driven applications.

Build Better Web Apps

I hope you're enjoying this article.

Get the best content on building better web apps delivered to you.