Convert and Loop through JSON with PHP and JavaScript Arrays/Objects | json to array php

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, we will learn about how to get data from json array in php with an example.

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 or jQuery Parsing PHP JSON Data.

json to array php Examples

PHP Converting an array to JSON Tutorial With Example
PHP Converting an array to JSON Tutorial With Example

I learn to this post into main 3 part:

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

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.

<?php
  // 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.

<?php
  // Loop through Array
  $dream11Arr = ...; // Replace ... with your PHP Array
  foreach ($dream11Arr as $key => $value) {
    echo $value["name"] . ", " . $value["player_type"] . "<br>";
  }

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

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.

<?php
  // 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+.
<?php
  $array = array(
    "foo" => "bar",
    "bar" => "foo"
  );

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


Convert JSON String to JavaScript Object

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

<script>
  // 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
</script>

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.

<script>
  // 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
</script>

Loop through JavaScript Object

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

<script>
  // 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"]);
    }
  }
</script>

Convert JavaScript Object to JSON String

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

<script>
  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);
  alert(JSONString);
</script>

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:

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.
index.html

<select id="player_type" name="player_type">
  <option value="batsmen">batsmen</option>
  <option value="bowlers">bowlers</option>
</select>

<table id="cricketer" border="1">
  <thead>
    <th>player Name</th>
    <th>player type</th>
  </thead>
  <tbody>

  </tbody>
</table>

<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script>
$("#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);
    }
  });
});
</script>

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.

<?php
  // 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;
?>

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.


Related FAQ

Here are some more FAQ related to this Article:

  1.   Converting JSON Object into Javascript PHP array
  2.   PHP nested FOR loop multiple conditions - ArrayIterator
  3.   Vue Toggle Switch Component ON-OFF
  4.   Receive JSON POST Data using PHP
  5.   Vue.js Tutorial for beginners
  6.   Bootstrap Product slider List Carousel for Ecommerce Website
  7.   Create JSON with json_encode and json_decode using PHP
  8.   How to Get the Value of Selected Option in a Combo Box Using jQuery?
  9.   Laravel 7 jQuery Ajax Form Validation Example
  10.   jQuery Parsing PHP JSON Data