PHP Object to Array Convert using JSON Decode

PHP Object to Array Convert using JSON Decode

PHP JSON decode; In this tutorial, you will learn how to convert json object to array in php using json_decode().

There are several ways to convert an object to an array in PHP, but using json_decode is one of the simplest and most efficient methods. In this article, you will learn with examples of how to use json_decode to convert an object to an array in PHP.

Before you dive into the details of using json_decode, let’s first understand what an object and an array are in PHP.

An object is an instance of a class, and it contains data in the form of properties and methods. On the other hand, an array is a collection of data elements, which can be of any data type. An array is indexed by keys, which can be either numeric or string.

One of the simplest and most effective ways to convert an object to an array in PHP is by using the json_decode() function. This function takes a JSON string as input and converts it into a PHP variable. By using the json_encode() function to convert an object into a JSON string, you can then use json_decode() to convert it into an array.

PHP: json_decode() | How to decode json to array in PHP

Now, let’s see how you can use json_decode to convert an object to an array in PHP.

Syntax:

The syntax of JSON decode function is:-

json_decode(string, assoc, depth=500, options)

Parameters of json_decode() function

  • json: It holds the JSON string which need to be decode. It only works with UTF-8 encoded strings.
  • assoc: It is a boolean variable. If it is true then objects returned will be converted into associative arrays.
  • depth: It states the recursion depth specified by user.
  • options: It includes bitmask of JSON_OBJECT_AS_ARRAY, JSON_BIGINT_AS_STRING,, JSON_THROW_ON_ERROR.

Ex 1 – Convert JSON String to PHP array

Let’s take the first example, here you will convert the JSON string to PHP array using the json_decode() function. See the example below:

<?php

$jObject = '{"Sam":23,"John":32,"Joe":41,"Elvish":43}';

var_dump(json_decode($jObject, true));
?>

The output of the above code is: Array ( [Sam] => 23 [John] => 32 [Joe] => 41 [Elvish] => 43 )

Ex 2 – json String to Multidimensional Array PHP

Let’s take the second example of json_decode() function, Here you will take to convert json multiple objects to a multidimensional array in PHP. Let’s see example:

<?php

$jObject = '[
    {
        "title": "PHP",
        "category": "PHP"
    },
    {
        "title": "JSON PHP",
        "category": "PHP"
    },
    {
        "title": "JSON string to array php",
        "category": "php"
    }
]';
//json_decode multidimensional array php
print_r(json_decode($jObject, true));
?>

The output of the above code is:

Array ( 
   [0] => Array ( [title] => PHP [category] => PHP ) 
   [1] => Array ( [title] => JSON PHP [category] => PHP ) 
   [2] => Array ( [title] => JSON string to array php [category] => php ) 
 ) 

Ex 3 – json decode and access object value php

Let’s take the third example, in this example, you will decode the json object first and after access the value by key. Let’s see the example:

<?php

$jsonObject= '{
    "title": "PHP JSON decode example",
    "category": "PHP"
}';


$res = json_decode($jsonObject);

// access title of reponse object
echo $res->title;

?>

The output of the above code is: ” PHP JSON decode example

Ex 4 -Convert object to an array in PHP

Here is an example of how to use json_decode() to convert an object to an array in PHP:

// Create a sample object
$myObject = new stdClass();
$myObject->name = "John";
$myObject->age = 30;
$myObject->country = "USA";

// Convert the object to a JSON string
$jsonString = json_encode($myObject);

// Convert the JSON string to an array using json_decode()
$array = json_decode($jsonString, true);

// Output the array to the console
print_r($array);

In the above example, you first create a sample object called $myObject with three properties: name, age, and country. You then convert the object into a JSON string using the json_encode() function.

Next, you use the json_decode() function to convert the JSON string back into a PHP variable. You pass true as the second argument to json_decode() to convert the result into an associative array.

Finally, you output the resulting array using the print_r() function. The output will be:

Array
(
    [name] => John
    [age] => 30
    [country] => USA
)

As you can see, the resulting array has the same keys and values as the original object.

Using json_decode() to convert an object to an array in PHP is a straightforward and effective technique. It allows you to manipulate data in an array format, even when you have an object with the data. This technique can be useful in many scenarios, such as when working with API responses or database queries that return objects.

Conclusion

Converting an object to an array is a common task in PHP, and json_decode provides a simple and efficient way to accomplish it. By following the steps outlined in this article, you can easily convert an object to an array using json_decode in PHP.

Recommended Posts

  1. PHP JSON encode – Convert Array To JSON or Object To JSON
  2. Functions: Remove First Character From String PHP
  3. Remove Specific/Special Characters From String In PHP
  4. How to Replace First and Last Character From String PHP
  5. Reverse String in PHP
  6. Array Push, POP PHP | PHP Array Tutorial
  7. PHP Search Multidimensional Array By key, value and return key
  8. remove duplicates from multidimensional array PHP
  9. PHP Remove Duplicate Elements or Values from Array PHP

AuthorAdmin

Greetings, I'm Devendra Dode, a full-stack developer, entrepreneur, and the proud owner of Tutsmake.com. My passion lies in crafting informative tutorials and offering valuable tips to assist fellow developers on their coding journey. Within my content, I cover a spectrum of technologies, including PHP, Python, JavaScript, jQuery, Laravel, Livewire, CodeIgniter, Node.js, Express.js, Vue.js, Angular.js, React.js, MySQL, MongoDB, REST APIs, Windows, XAMPP, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL, and Bootstrap. Whether you're starting out or looking for advanced examples, I provide step-by-step guides and practical demonstrations to make your learning experience seamless. Let's explore the diverse realms of coding together.

Leave a Reply

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