How to get data from multidimensional json array in php?


In the previous pages, we have described arrays that are a single list of key/value pairs.

However, sometimes you want to store values with more than one key. For this, we have multidimensional arrays.


PHP - Multidimensional Arrays

A multidimensional array is an array containing one or more arrays.

PHP supports multidimensional arrays that are two, three, four, five, or more levels deep. However, arrays more than three levels deep are hard to manage for most people.

The dimension of an array indicates the number of indices you need to select an element.

  • For a two-dimensional array you need two indices to select an element
  • For a three-dimensional array you need three indices to select an element


PHP - Two-dimensional Arrays

A two-dimensional array is an array of arrays (a three-dimensional array is an array of arrays of arrays).

First, take a look at the following table:

NameStockSold
Volvo 22 18
BMW 15 13
Saab 5 2
Land Rover 17 15

We can store the data from the table above in a two-dimensional array, like this:

$cars = array (
  array("Volvo",22,18),
  array("BMW",15,13),
  array("Saab",5,2),
  array("Land Rover",17,15)
);

Now the two-dimensional $cars array contains four arrays, and it has two indices: row and column.

To get access to the elements of the $cars array we must point to the two indices (row and column):

Example

<?php
echo $cars[0][0].": In stock: ".$cars[0][1].", sold: ".$cars[0][2].".<br>";
echo $cars[1][0].": In stock: ".$cars[1][1].", sold: ".$cars[1][2].".<br>";
echo $cars[2][0].": In stock: ".$cars[2][1].", sold: ".$cars[2][2].".<br>";
echo $cars[3][0].": In stock: ".$cars[3][1].", sold: ".$cars[3][2].".<br>";
?>

Try it Yourself »

We can also put a for loop inside another for loop to get the elements of the $cars array (we still have to point to the two indices):

Example

<?php
for ($row = 0; $row < 4; $row++) {
  echo "<p><b>Row number $row</b></p>";
  echo "<ul>";
  for ($col = 0; $col < 3; $col++) {
    echo "<li>".$cars[$row][$col]."</li>";
  }
  echo "</ul>";
}
?>

Try it Yourself »


Complete PHP Array Reference

For a complete reference of all array functions, go to our complete PHP Array Reference.

The reference contains a brief description, and examples of use, for each function!



Associative Array: It is used to store key-value pairs.,Multidimensional arrays in PHP,Indexed Array: It is an array with a numeric key. It is basically an array wherein each of the keys is associated with its own specific value.,Multidimensional Array: It is a type of array which stores another array at each index instead of a single element. In other words, define multi-dimensional arrays as array of arrays. 

[{
      "name": "Pankaj Singh",
      "age": "20"
   },
   {
      "name": "Arun Yadav",
      "age": "21"
   },
   {
      "name": "Apeksha Jaiswal",
      "age": "20"
   }
]

{
   "first": {
      "id": 1,
      "product_name": "Doorbell",
      "cost": 199
   },
   "second": {
      "id": 2,
      "product_name": "Bottle",
      "cost": 99
   },
   "third": {
      "id": 3,
      "product_name": "Washing Machine",
      "cost": 7999
   }
}


Suggestion : 2

Defination:- The PHP json_encode() function is used to convert PHP array or object into JSON.,The PHP json_encode() function is used to convert PHP array or object into JSON object. PHP has some pre inbuilt functions to handle JSON.,We will take an example for convert PHP array to JSON or get data from JSON array in PHP using the PHP json_encode() function.,If you want to convert multidemsional array to json in PHP using the json_encode() function. Let’s see the example below:

Syntax

json_encode(value, options);

2._

< ? php

$arr = array('name' => 'test', 'email' => '[email protected]', 'mobile' => '88888xxxx', 'age' => 25);
echo json_encode($arr).
"\n";

?
>

3._

< ? php

class Color {

}

$color = new Color();
$color - > title = 'Block';
$color - > code = 'FFF';

$json = json_encode($color);
echo $json.
"\n";

?
>

< ? php

$arr = array('name' => 'test', 'email' => '[email protected]', 'mobile' => '88888xxxx', 'age' => 25);
echo json_encode($arr).
"\n";

?
>

< ? php

class Color {

}

$color = new Color();
$color - > title = 'Block';
$color - > code = 'FFF';

$json = json_encode($color);
echo $json.
"\n";

?
>

< ? php

$string = "hello php dev";
echo json_encode($string).
"\n";

?
>

< ? php

$arr = array('Name' => 'Test',
   'Age' => 24,
   'Email' => '[email protected]');
echo json_encode($arr).
"\n";

?
>


Suggestion : 3

To convert multi-dimensional array into json in PHP, use the json_encode() function. Let’s see an example where we can encode the multidimensional array.,To convert String to JSON in PHP, use the json_encode() function. PHP json_encode() function is useful to convert String to JSON object.,Arrays in PHP will also be converted into JSON when using the PHP function json_encode(). You can find the example of covert PHP Array to JSON.,The json_encode() function returns a string, if the function works.

If you’re passing JSON data to a javascript program, make sure your program begins with:

< ? php
header('Content-Type: application/json'); ?
>

2._

json_encode(value, options)

Let’s see the following example.

< ? php



$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
echo json_encode($arr).
"\n";


Suggestion : 4

This example PHP array is mixed, with the outer level numerically indexed and the second level associative:,The first example array has two levels, both numerically indexed. ,The following demonstrates how to access elements in the multi-dimensional numerically indexed array:,PHP Arrays to JS Using json_encode

var ar = < ? php echo json_encode($ar) ? > ;

var ar = JSON.parse('<?php echo json_encode($ar) ?>');

<?php

$products = array(
    
    array('choc_cake', 'Chocolate Cake', 15),
    array('carrot_cake', 'Carrot Cake', 12),
    array('cheese_cake', 'Cheese Cake', 20),
    array('banana_bread', 'Banana Bread', 14)
);
?>
<script type="text/javascript">
   
   var products = < ? php echo json_encode($products) ? > ;

   
   

   
   alert(products[0][1]); 
</script>

alert(products[0][1]); // Chocolate Cake


Suggestion : 5

First, the json_encode($array) converts the entire multi-dimensional array to a JSON string. Then the json_decode($string) will convert the JSON string to a stdClass object.,Best Way to Multidimensional Array to Object Convert using PHP JSON Encode/Decode,2. Convert Multidimensional Array to Object using array_map,Example 2: Convert PHP Multidimensional Array to Object using array_map

1._

$arr = array(
   'laptop' => 'appleMarutiMaruti',
   'book' => 'MarutiappleMaruti',
   'tv' => 'MarutiMarutiapple',
);

$get_object = (object) $arr;

print_r($get_object);




echo $get_object - > book;

PHP Array: Associative, Multidimensional

$get_object = json_decode(json_encode($array));

Accessing All Array Elements in Nested Arrays

function multi_dimensional_arr_to_obj($arr) {
   return (is_array($arr) ? (object) array_map(__FUNCTION__, $arr) : $arr);
}

$get_object = multi_dimensional_arr_to_obj($array);


Suggestion : 6

A real-world scenario is to return an array of arrays from PHP as a JSON string, using json_encode. Here’s how that works. This code:,If you need to see a simple PHP example that converts an array of data to a JSON string using the json_encode function, I hope this little script is helpful:,As you can see, in the PHP code I have an array of arrays that map a stock symbol to its price, and convert that to JSON by calling json_encode, and the code results in the output shown.,I omitted a lot from that script, but as you can see at the end of the script, I use the PHP json_encode method to convert a PHP array to JSON.

If you need to see a simple PHP example that converts an array of data to a JSON string using the json_encode function, I hope this little script is helpful:

< ? php

#
# do some stuff here...
   #

# send a json reply back to the sencha client
header('Content-type: text/html');
echo json_encode(array(
   "success" => true,
   "msg" => $message,
   "id" => $id
));

?
>

The output from that script varies depending on the values of $message and $id=, but some sample output looks like this JSON string:

{
   "success": true,
   "msg": "",
   "id": 100
}

A real-world scenario is to return an array of arrays from PHP as a JSON string, using json_encode. Here’s how that works. This code:

< ? php

header('Content-type: text/html');
echo json_encode(
   array(
      array('symbol' => 'AAPL', 'price' => '525.00'),
      array('symbol' => 'GOOG', 'price' => '600.00'),
      array('symbol' => 'TSLA', 'price' => '220.00')
   )
);

?
>


Suggestion : 7

You can recursively search for by key or value inside a nested JSON with a slight modification to the code above. All you need is to defina a function that takes two arguments - an array and a Key/Value. You then run the same recursion as before but you have another if condition to check for the specified key/value.,In the above code, the print_recursive function calls itself if the value is an array otherwise prints the key and value.,If you have an array inside a nested JSON object then use two foreach loops to access the inner array element.,Let\'s start with a simple code snippet to print all the keys and values in our sample JSON document.

A JSON document can have JSON objects nested inside other JSON objects. JSON objects are key-value pairs and there are different methods you can use to access JSON objects from a nested JSON document. One method is to use recursion just like you access data from a nested array or tree data structure. Another method is to use loops. Let's look at some examples for accessing data a nested JSON document like below.

[{
      "id": 1,
      "name": "Max Adams",
      "born": "21 Oct 2001",
      "cars": [{
            "make": "Mercedes",
            "model": "GLS"
         },
         {
            "make": "Audi",
            "model": "Q8"
         }
      ],
      "favourite": {
         "colour": "Blue",
         "movie": "Toy Story"
      }
   },
   {
      "id": 2,
      "name": "Steven Miller",
      "born": "28 Jul 2004",
      "cars": [{
         "make": "Tesla",
         "model": "Model S"
      }],
      "favourite": {
         "colour": "Red",
         "movie": "Mulan"
      }
   },
   {
      "id": 3,
      "name": "Daniel James",
      "born": "18 Dec 2005",
      "cars": [{
         "make": "Bugatti",
         "model": "Chiron"
      }],
      "favourite": {
         "colour": "Yellow",
         "movie": "Frozen",
         "toy": "Teddy"
      }
   }
]

Consider that our example JSON is stored in a file named "persons.txt". Firstly read the contents of the text file into a string variable using the file_get_contents() function and then use json_decode() function to convert the JSON string to a PHP variable.

$filepath = './persons.txt';
$json_string = file_get_contents($filepath);
$json = json_decode($json_string, true);

To access the objects inside a JSON array, the simplest and easiest method is to use a foreach loop to iterate through the array elements and fetch the data that you need. For example, to print all the name and id numbers from our example JSON document:

foreach($json_array as $elem)  {
   echo($elem['id']. ", ".$elem['name'] );
   echo("<br/>");
}

2, Steven Miller
3, Daniel James

Max Adams - Blue
Steven Miller - Red
Daniel James - Yellow


Suggestion : 8

A deep dive into looping multidimensional JSON arrays,Using nested foreach to loop through a multidimensional json array with PHP,There are 3 steps to looping through multidimensional JSON arrays in PHP. You need to use json_decode to convert the string into a PHP array, loop through it, and then use json_encode to convert it back to a JSON string.,Using RecursiveArrayIterator to loop through a multidimensional json array with PHPWhy RecursiveArrayIterator?

Let’s assume that we have a JSON response with hotels 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"

      }
   }

}

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


$json = file_get_contents("hotels.json", false);


$json_array = json_decode($json, true);


foreach($json_array as $id => $hotel) {
      
      foreach($hotel as $key => $value) {
         
         if (is_array($value)) {
            
            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 ===
   === === === === === === === === === === ===


How to get data from JSON nested array in PHP?

Firstly read the contents of the text file into a string variable using the file_get_contents() function and then use json_decode() function to convert the JSON string to a PHP variable. $filepath = './persons. txt'; $json_string = file_get_contents($filepath); $json = json_decode($json_string, true);

How to access nested JSON object in PHP?

$url = file_get_contents("http://blahblahblahblah"); $arr = json_decode($url,true);

How to get data from JSON array in PHP using for loop?

“loop through json array php” Code Answer.
$arr = json_decode('[{"var1":"9","var2":"16","var3":"16"},{"var1":"8","var2":"15","var3":"15"}]');.
foreach($arr as $item) { //foreach element in $arr..
$uses = $item['var1']; //etc..

How do you loop through a multidimensional array in PHP?

Answer: Use the PHP nested loop You can simply use the foreach loop in combination with the for loop to access and retrieve all the keys, elements or values inside a multidimensional array in PHP.