Convert and Loop through JSON with PHP and JavaScript Arrays/Objects

pakainfocom profile image pakainfo ・6 min read

Today, We want to share with you json to array php.In this post we will show you json_decode to array php, hear for php parse json array we will give you demo and example for implement.In this post.

If you’re working with client side JSON (JavaScript Object Notation) as well as either required to easy convert a JSON string to array or object as well as loop through it or vice-versa, take an array or object as well as convert it to a JSON string to return, both can be done in PHP sever side or client side JavaScript.

json to array php Examples

I learn to this post into main 3 part:

  • Using with PHP
  • Using with JavaScript
  • Using with both PHP and JavaScript

ALSO READ: json to array php and JavaScript Arrays/Objects

Convert JSON String to PHP Array or Object

PHP >= 5.2.0 some features a function available, like as a json_decode, that decodes a JSON data string into a PHP variable. By native it data returns an object. The second arguments accepts a boolean value like as a true or false that when set as true, tells it to return the objects as associative arrays. You can learn more about the php json_decode function from PHP’s offiecal documentation.

  // JSON string
  $fetchPlayerJson = '[{"name":"Virat Kohli","player_type":"batsmen"},{"name":"Dhoonee Sharmas","player_type":"batsmen"},{"name":"Rohitsir Sharma  ","player_type":"bowlers"}]';

  // Convert JSON string to Array
  $dream11Arr = json_decode($fetchPlayerJson, true);
  print_r($dream11Arr);        // print all data of the Array
  echo $dream11Arr[0]["name"]; // Retrieves Array data

  // Convert JSON string to Object
  $someObject = json_decode($fetchPlayerJson);
  print_r($someObject);      // print all data of the Object
  echo $someObject[0]->name; // Retrieves Object data

Loop through PHP Array or Object

Loop through a PHP array or object with a foreach loop.

 $value) {
    echo $value["name"] . ", " . $value["player_type"] . "
"; } // Loop through Object $someObject = ...; // Replace ... with your PHP Object foreach($someObject as $key => $value) { echo $value->name . ", " . $value->player_type . "
"; } ?>

Note the differences in Retrieving the values of an array vs an object.

Convert PHP Array or Object to JSON String

PHP also features a json_encode function to convert an array or object into a string. Read more about the json_encode function from PHP’s documentation.

  // Array
  $dream11Arr = [
      "name"   => "Virat Kohli",
      "player_type" => "batsmen"
      "name"   => "Dhoonee Sharmas",
      "player_type" => "batsmen"
      "name"   => "Rohitsir Sharma  ",
      "player_type" => "bowlers"

  // Convert Array to JSON String
  $fetchPlayerJson = json_encode($dream11Arr);
  echo $fetchPlayerJson;

Note that I’m using the short array syntax that’s featured in PHP 5.4+.

  $array = array(
    "foo" => "bar",
    "bar" => "foo"

  // as of PHP 5.4
  $array = [
    "foo" => "bar",
    "bar" => "foo"

jQuery Parsing PHP JSON Data.

Convert JSON String to JavaScript Object

JavaScript has a built-in JSON.parse() method that parses a JSON string and returns an object.

  // Convert JSON String to JavaScript Object
  var JSONString = '[{"name":"Virat Kohli","player_type":"batsmen"},{"name":"Dhoonee Sharmas","player_type":"batsmen"},{"name":"Rohitsir Sharma","player_type":"bowlers"}]';

  var PLAYERJSONObj = JSON.parse(JSONString);
  console.log(PLAYERJSONObj);      // print all data of the Object in the console
  alert(PLAYERJSONObj[0]["name"]); // Retrieves Object data

JSON.parse() is very well-supported, but there are browsers that do not support it (i.e. <= IE 7. More information at pakainfo.com).

jQuery 1.x has a $.parseJSON() method that should fill in the gaps for those browsers if you are needing to support them. You can also use the JSON-js library as a polyfill.

  // Convert JSON String to JavaScript Object with jQuery
  var JSONString = "..."; // Replace ... with your JSON String

  var PLAYERJSONObj = $.parseJSON(JSONString);
  console.log(PLAYERJSONObj);      // print all data of the Object in the console
  alert(PLAYERJSONObj[0]["name"]); // Retrieves Object data

Loop through JavaScript Object

You can then loop through a JavaScript object using a for in loop.

  // Loop through Object
  var PLAYERJSONObj = ...; // Replace ... with your JavaScript Object

  for (var key in PLAYERJSONObj) {
    if (PLAYERJSONObj.hasOwnProperty(key)) {
      console.log(PLAYERJSONObj[key]["name"] + ", " + PLAYERJSONObj[key]["player_type"]);

Convert JavaScript Object to JSON String

JavaScript has a JSON.stringify method to convert a value into a JSON string.

  var PLAYERJSONObj = [
      "name": "Virat Kohli",
      "player_type": "batsmen"
      "name": "Dhoonee Sharmas",
      "player_type": "batsmen"
      "name": "Rohitsir Sharma  ",
      "player_type": "bowlers"

  var JSONString = JSON.stringify(PLAYERJSONObj);

Like JSON.parse, JSON.stringify is not supported in dinosaur browsers like <= IE 7. You can use the JSON-js library to polyfill JSON.stringify as well.

You can merge the great ways above to make a powerful, easy, dynamic step by step implementations on your website or single page web application.

Let’s say you want to fetch all the details from a database, safely very fast and light weight data return the data as JSON, and loop through it dynamically, you can do therefor with a bit of PHP server side and client side JavaScript with jquery Ajax.

Dynamically Get JSON via Ajax and Loop Through JSON

Let’s assume your mysql database structure looks like the following simple data:

Table: cricketer
| id | name               | type    |
| 0  | Virat KohliS       | batsmen |
| 1  | Dhoonee Sharmas    | batsmen |
| 2  | Rohitsir Sharma    | bowlers |
| 3  | Yuvaraj shinhs     | bowlers |
| 4  | Virendra Shevangs  | bowlers |

And you want to jquery ajax with PHP dynamically get a list of cricketer from the database based on player_type, like this:
json to array php
Let’s start bellow source code with the front-end file step by step make a simple index.html that’ll have a simple select dropdown HTML Forms with player_types to select from, a cricketer table to display the results, and the script to handle the jquery Ajax. The JavaScript is written in jQuery.


player Name player type
$("#player_type").on("change", function() { $.ajax({ type: "POST", data: { "player_type": $("#player_type").val() }, url: "response.php", dataType: "json", success: function(PLAYERJSONObj) { var cricketerHTML = ""; // Loop through Object and create cricketerHTML for (var key in PLAYERJSONObj) { if (PLAYERJSONObj.hasOwnProperty(key)) { cricketerHTML += "<tr>"; cricketerHTML += "<td>" + PLAYERJSONObj[key]["name"] + "</td>"; cricketerHTML += "<td>" + PLAYERJSONObj[key]["player_type"] + "</td>"; cricketerHTML += "</tr>"; } } // Replace table’s tbody html with cricketerHTML $("#cricketer tbody").html(cricketerHTML); } }); });

Now let’s last step to make a player_results.php file to handle the back-end logic of getting the details from the database as well as returning the results as a JSON data string.

  // File: player_results.php

  // Get POST player_type value
  $player_type = $_POST["player_type"];

  // Connect to the database
  // replace the parameters with your proper credentials
  $connection = mysqli_connect("localhost", "username", "password", "database_name");

  // Query to run
  $query = mysqli_query($connection,
           "SELECT * FROM cricketer WHERE player_type = '" . $player_type . "'");

  // Create empty array to hold query results
  $dream11Arr = [];

  // using Loop through query and push results into $dream11Arr;
  while ($row = mysqli_fetch_assoc($query)) {
    array_push($dream11Arr, [
      'name'   => $row['name'],
      'player_type' => $row['player_type']

  // PHP Convert the Array to a JSON String and echo it
  $fetchPlayerJson = json_encode($dream11Arr);
  echo $fetchPlayerJson;

json to array php

To fetch a more in-depth as well as very useful example of simply step by step PHP-JSON-JavaScript/jQuery-Ajax interaction, also you can read my new articles for jQuery Ajax Call to PHP Script with JSON Return post.

I hope you get an idea about json to array php. I would like to have feedback on my infinityknow.com blog. Your valuable feedback, question, or comments about this article are always welcome. If you enjoyed and liked this post, don’t forget to share.

Posted on by:

pakainfocom profile



My name is Angular King. I'm a full-stack developer, entrepreneur and owner of Pakainfo. I live in India and I love to write


Editor guide