{"id":123305,"date":"2021-09-15T18:07:39","date_gmt":"2021-09-15T18:07:39","guid":{"rendered":"https:\/\/phppot.com\/?p=15597"},"modified":"2021-09-15T18:07:39","modified_gmt":"2021-09-15T18:07:39","slug":"php-object-to-array-convert-using-json-decode","status":"publish","type":"post","link":"https:\/\/sickgaming.net\/blog\/2021\/09\/15\/php-object-to-array-convert-using-json-decode\/","title":{"rendered":"PHP Object to Array Convert using JSON Decode"},"content":{"rendered":"<div class=\"modified-on\" readability=\"7.1666666666667\"> by <a href=\"https:\/\/phppot.com\/about\/\">Vincy<\/a>. Last modified on September 15th, 2021.<\/div>\n<p>The PHP object to array conversion makes it easy to access data from the object bundle. Most of the API outputs object as a response.<\/p>\n<p>Some APIs may return a complex object structure. For example, a mixture of objects and arrays bundled with a response. At that time, the object to array conversion process will simplify the data parsing.<\/p>\n<p>This quick example performs a PHP object to array conversion in a single step. It creates an object bundle and sets the properties.<\/p>\n<p>It uses <a href=\"https:\/\/phppot.com\/php\/php-json-encode-and-decode\/\">JSON encode() decode()<\/a> function for the conversion.&nbsp;The json_decode() supplies boolean true to get the array output.<\/p>\n<div class=\"post-section-highlight\" readability=\"37\">\n<h2>Quick example<\/h2>\n<p class=\"code-heading\">PHP object to array conversion in a line using json_decode<\/p>\n<pre class=\"prettyprint\"><code class=\"language-php\">\n&lt;?php\n$object = new StdClass();\n$object-&gt;id = 5678;\n$object-&gt;name = \"William\";\n$object-&gt;department = \"CSE\";\n$object-&gt;designation = \"Engineer\"; $result = json_encode($object);\n\/\/ converts object $result to array\n$output = json_decode($result, true); print \"&lt;pre&gt;\";\nprint_r($result);\n?&gt;\n<\/code><\/pre>\n<\/div>\n<h4>Output<\/h4>\n<p>After <a href=\"https:\/\/phppot.com\/php\/url-encoding-and-decoding-in-php\/\">decoding<\/a>, the output array is printed to the browser. The below screenshot shows the output of this program.<\/p>\n<p><img decoding=\"async\" loading=\"lazy\" class=\"alignnone size-full wp-image-15619\" src=\"https:\/\/phppot.com\/wp-content\/uploads\/2021\/09\/php-object-to-array.jpg\" alt=\"php object to array\" width=\"230\" height=\"194\"><\/p>\n<h2>Different ways of converting a PHP object to array<\/h2>\n<p>When converting an object to array, the object property \u2018name:value\u2019 pairs will form an associative array.<\/p>\n<p>If an object contains unassigned properties then it will return an array with numerical keys.<\/p>\n<p>There are two ways to achieve a PHP object to array conversion.<\/p>\n<ol>\n<li><em>Typecasting<\/em> object into an array.<\/li>\n<li><em>Encoding and decoding<\/em> object properties into an array of elements.<\/li>\n<\/ol>\n<p>Typecasting is a straightforward method to convert the type of input data. The second method applies json_decode() on the given object. It supplied boolean true as a second parameter to get the output in an array format.<\/p>\n<p>This article includes examples of using both of the above methods to perform the object to array conversion.<\/p>\n<h2>PHP object to array using typecasting<\/h2>\n<p>This is an alternate method to convert an object type into an array. The below program uses the same input object.<\/p>\n<p>It replaces the JSON encode decode via conversion with the <a href=\"https:\/\/phppot.com\/php\/php-data-type-conversion\/\">typecasting<\/a> statement. The output will be the same as we have seen above.<\/p>\n<p>The PHP typecasting syntax is shown below. It prepends the target data type enclosed with parenthesis.<\/p>\n<pre class=\"prettyprint\"><code class=\"language-php\">\n$output = (target-data-type) $input\n<\/code><\/pre>\n<p class=\"code-heading\">type-casting-to-convert-object-to-array.php<\/p>\n<pre class=\"prettyprint\"><code class=\"language-php\">\n&lt;?php\n$object = new StdClass();\n$object-&gt;id = 5678;\n$object-&gt;name = \"William\";\n$object-&gt;department = \"CSE\";\n$object-&gt;destination = \"Engineer\"; print\"&lt;pre&gt;\";\nprint_r( (array) $object );\n?&gt;\n<\/code><\/pre>\n<h2>Recursive object to array conversion<\/h2>\n<p>This example uses an input object with depth = 3. It adds more properties at a <a href=\"https:\/\/phppot.com\/css\/multilevel-dropdown-menu-with-pure-css\/\">nested level<\/a> at different depths. The hierarchical object bundle is set as the input for the conversion process.<\/p>\n<p>This program defines a custom function to convert a PHP object to array. It performs the conversion recursively on each level of the input object.<\/p>\n<p class=\"code-heading\">converting-recursive-object-to-array.php<\/p>\n<pre class=\"prettyprint\"><code class=\"language-php\">\n&lt;?php\n$object = new StdClass();\n$object-&gt;id = 5678;\n$object-&gt;name = \"William\"; $object-&gt;address = new stdClass();\n$object-&gt;address-&gt;email = \"William@gmail.com\"; $object-&gt;address-&gt;billing = new stdClass();\n$object-&gt;address-&gt;billing-&gt;zipcode = 9950; $object-&gt;address-&gt;shipping = new stdClass();\n$object-&gt;address-&gt;shipping-&gt;zipcode = 1234; $object-&gt;address-&gt;state = \"South Carolina\";\n$object-&gt;address-&gt;city = \"Columbia\";\n$object-&gt;address-&gt;country = \"US\"; function objectToArray($object)\n{ foreach ($object as $k =&gt; $obj) { if (is_object($obj)) { $object-&gt;$k = objectToArray($obj); } else { $object-&gt;$k = $obj; } } return (array) $object;\n} $result = objectToArray($object); print \"&lt;pre&gt;\";\nprint_r($result);\n?&gt;\n<\/code><\/pre>\n<p>This is the output of the recursive PHP object to the array conversion program above.<\/p>\n<p><img decoding=\"async\" loading=\"lazy\" class=\"alignnone size-full wp-image-15625\" src=\"https:\/\/phppot.com\/wp-content\/uploads\/2021\/09\/recursive-object-to-array-conversion.jpg\" alt=\"recursive object to array conversion\" width=\"300\" height=\"427\" srcset=\"https:\/\/phppot.com\/wp-content\/uploads\/2021\/09\/recursive-object-to-array-conversion.jpg 300w, https:\/\/phppot.com\/wp-content\/uploads\/2021\/09\/recursive-object-to-array-conversion-211x300.jpg 211w\" sizes=\"auto, (max-width: 300px) 100vw, 300px\"><\/p>\n<h2>Convert PHP class object into array<\/h2>\n<p>This example constructs a PHP class object bundle. The <a href=\"https:\/\/phppot.com\/php\/php-constructors-destructors\/\">class constructor<\/a> sets the properties of the object during the instantiation.<\/p>\n<p>Then, the Student class instance is encoded to prepare object type data. The json_encode() function prepares the JSON object to supply it for decoding. The json_decode() converts the PHP object to array.<\/p>\n<p class=\"code-heading\">convert-class-object-into-array.php<\/p>\n<pre class=\"prettyprint\"><code class=\"language-php\">\n&lt;?php\nclass student\n{ public function __construct($id, $name, $state, $city, $country) { $this-&gt;id = $id; $this-&gt;name = $name; $this-&gt;state = $state; $this-&gt;city = $city; $this-&gt;country = $country; }\n} $student = new student(\"5678\", \"William\", \"South Carolina\", \"Columbia\", \"US\");\n$result = json_encode($student);\n$output = json_decode($result, true);\nprint \"&lt;pre&gt;\";\nprint_r($output);\n?&gt;\n<\/code><\/pre>\n<h2>Check is_object() before conversion<\/h2>\n<p>It is <a href=\"https:\/\/medium.com\/techlaboratory\/php-programming-best-practices-and-coding-styles-e43234446fd3\" target=\"_blank\" rel=\"noopener\">good programming practice<\/a> to check the data availability before processing. This example applies the is_object verification before converting a PHP object to an array.<\/p>\n<p>This method verifies if the input is an object. PHP includes exclusive functions to verify data availability and its type. Example <a href=\"https:\/\/phppot.com\/php\/isset-vs-empty-vs-is_null\/\">isset(), empty()<\/a>, is_array() etc.<\/p>\n<p class=\"code-heading\">checking-object-before-conversion.php<\/p>\n<pre class=\"prettyprint\"><code class=\"language-php\">\n&lt;?php class student\n{ public function __construct($id, $name, $state, $city, $country) { $this-&gt;id = $id; $this-&gt;name = $name; $this-&gt;state = $state; $this-&gt;city = $city; $this-&gt;country = $country; }\n}\n$student= new student(\"5678\", \"William\", \"South Carolina\", \"Columbia\", \"US\"); print \"&lt;pre&gt;\";\nif (is_object($student)) { echo \"Input Object:\" . '&lt;br&gt;'; $result = json_encode($student); print_r($result); $studentArray = json_decode($result, true);\n} if(!empty($studentArray) &amp;&amp; is_array($studentArray)) { echo \"&lt;br&gt;&lt;br&gt;Output Array:\" . '&lt;br&gt;'; print_r($studentArray);\n}\n?&gt;\n<\/code><\/pre>\n<h2>Convert Private, Protected object of a class<\/h2>\n<p>The below program defines a class with <a href=\"https:\/\/phppot.com\/php\/php-inheritance\/\">private and protected properties<\/a>. The PHP code instantiates the class and creates an object bundle.<\/p>\n<p>It uses both the typecasting and decoding methods to convert the object into an array.<\/p>\n<p>When using typecasting, the output array index of the private property contains the class name prefix. After conversion, the array index has a * prefix for the protected properties.<\/p>\n<p class=\"code-heading\">converting-private-protected-object.php<\/p>\n<pre class=\"prettyprint\"><code class=\"language-php\">\n&lt;?php\nclass Student\n{ public $name; private $id; protected $email; public function __construct() { $this-&gt;name =\"William\"; $this-&gt;id = 5678; $this-&gt;email = \"william@gmail.com\"; }\n} print \"&lt;pre&gt;\";\n$student = new Student;\n$result = json_encode($student);\n$output1 = json_decode($result, true);\nprint \"&lt;br\/&gt;Using JSON decode:&lt;br\/&gt;\";\nprint_r($output1); $output2 = new Student;\nprint \"&lt;br\/&gt;&lt;br\/&gt;Using Type casting:&lt;br\/&gt;\";\nprint_r( (array) $output2 );\n?&gt;\n<\/code><\/pre>\n<p>This output screenshot shows the difference in the array index. Those are created from the private and protected properties of the class instance.<\/p>\n<p><img decoding=\"async\" loading=\"lazy\" class=\"alignnone size-full wp-image-15629\" src=\"https:\/\/phppot.com\/wp-content\/uploads\/2021\/09\/private-protected-properties.jpg\" alt=\"private protected properties\" width=\"250\" height=\"224\"><\/p>\n<h2>Accessing object properties with numeric keys<\/h2>\n<p>This code includes an <a href=\"https:\/\/phppot.com\/php\/power-of-php-arrays\/\">associative array<\/a> of student details. It also contains values with numeric keys.<\/p>\n<p>When converting this array into an object, the associative array keys are used to access the object property values. There are exceptions to access properties if it doesn\u2019t have a name.<\/p>\n<p>The below code shows how to access objects with numeric keys. The key is enclosed by curly brackets to get the value.<\/p>\n<p class=\"code-heading\">problem-with-numerical-keys.php<\/p>\n<pre class=\"prettyprint\"><code class=\"language-php\">\n&lt;?php\n$inputArray = array( 'name' =&gt; 'William', 'email' =&gt; 'William@gmail.com', 'phone' =&gt; '12345678', 'REG5678'\n); $student = (object) array( 'name' =&gt; 'William', 'email' =&gt; 'William@gmail.com', 'phone' =&gt; '12345678', 'REG5678'\n);\necho '&lt;pre&gt;' . print_r($student, true) . '&lt;\/pre&gt;';\necho '&lt;br \/&gt;' . $student-&gt;name;\necho '&lt;br \/&gt;' . $student-&gt;email;\necho '&lt;br \/&gt;' . $student-&gt;phone;\necho '&lt;br \/&gt;' . $student-&gt;{0};\n?&gt;\n<\/code><\/pre>\n<h2>Conclusion<\/h2>\n<p>We have seen the different ways of converting a PHP object to an array. The basic PHP typecasting has achieved an object conversion except for few special cases.<\/p>\n<p>The PHP JSON encode decode process made the conversion with one line code. It accepts class objects and converts their properties into an <a href=\"https:\/\/web.stanford.edu\/class\/archive\/cs\/cs108\/cs108.1082\/106a-java-handouts\/HO49ArrayList.pdf\" target=\"_blank\" rel=\"noopener\">array list<\/a>.<\/p>\n<p>The custom function processes recursive object to array conversion. It is to handle complex objects with mixed objects or arrays as its child elements.<br \/><a class=\"download\" href=\"https:\/\/phppot.com\/downloads\/php-object-to-array-convert.zip\">download<\/a><\/p>\n<p> <!-- #comments --> <\/p>\n<div class=\"related-articles\">\n<h2>Popular Articles<\/h2>\n<\/p><\/div>\n<p> <a href=\"https:\/\/phppot.com\/php\/php-object-to-array\/#top\" class=\"top\">\u2191 Back to Top<\/a> <\/p>\n","protected":false},"excerpt":{"rendered":"<p>by Vincy. Last modified on September 15th, 2021. The PHP object to array conversion makes it easy to access data from the object bundle. Most of the API outputs object as a response. Some APIs may return a complex object structure. For example, a mixture of objects and arrays bundled with a response. At that [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":123306,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[65],"tags":[],"class_list":["post-123305","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-php-updates"],"_links":{"self":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/123305","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/comments?post=123305"}],"version-history":[{"count":0,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/123305\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/media\/123306"}],"wp:attachment":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/media?parent=123305"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/categories?post=123305"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/tags?post=123305"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}