Scroll to top
© 2022, Empty Code | All Rights Reserved
Share

JSON String to PHP Array/Object


Rahul Kumar Sharma - October 17, 2019 - 0 comments

Converting JSON String to PHP Array can be done by using the json_decode()function. By default, it returns an object. The second parameter accepts a Boolean that when set as true tells it to return the objects as associative arrays.

<?php
  // JSON string
  $sampleJSON = '[{"name":"Rohan Kumar","gender":"Male","age":"22"},{"name":"Ravi Kumar","gender":"Male","age":"20"},{"name":"Shivam Kumar","gender":"Male","age":"25"}]';

  // Converting JSON string to Array
  $sampleArray = json_decode($sampleJSON, true);
  print_r($sampleArray);
  echo $sampleArray[1]["name"]; // print: Ravi Kumar
  
  // Converting JSON string to Object
  $sampleObject = json_decode($sampleJSON);
  print_r($sampleObject); 
  echo $sampleObject[0]->name;
?>

Loop through PHP Array/Object

We will use foreach which provides an easy way to iterate over arrays. foreach works only on arrays and objects, and will issue an error when you try to use it on a variable with a different data type or an uninitialized variable.

<?php 
$sampleArray = [
    [
      "name"   => "Rohan Kumar",
      "gender" => "Male",
      "age" => "22"
    ],
    [
      "name"   => "Ravi Kumar",
      "gender" => "Male",
      "age" => "20"
    ],
    [
      "name"   => "Shivam Kumar",
      "gender" => "Male",
      "age" => "25"
    ]
];

// Loop through Array
foreach ($sampleArray as $key => $value) {
  echo $value["name"] . ", " . $value["gender"] . ", " . $value["age"] . "<br>";
}

// Loop through Object
foreach ($sampleObject as $key => $value) {
  echo $value->name . ", " . $value->gender . ", " . $value->age . "<br>";
}
?>

Convert PHP Array or Object to JSON

Converting PHP Array or Object to JSON can be done by using json_encode() function. json_encode() returns a string containing the JSON representation of the supplied value.
To know more: https://www.php.net/manual/en/function.json-encode.php

<?php 
$sampleArray = [
    [
      "name"   => "Rohan Kumar",
      "gender" => "Male",
      "age" => "22"
    ],
    [
      "name"   => "Ravi Kumar",
      "gender" => "Male",
      "age" => "20"
    ],
    [
      "name"   => "Shivam Kumar",
      "gender" => "Male",
      "age" => "25"
    ]
];

// Convert Array to JSON String
$sampleJSON = json_encode($sampleArray);
echo $sampleJSON;
?>

Related posts

Post a Comment

Your email address will not be published. Required fields are marked *