Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] PHP Object to Array Convert using JSON Decode

#1
PHP Object to Array Convert using JSON Decode

<div style="margin: 5px 5% 10px 5%;"><img src="https://www.sickgaming.net/blog/wp-content/uploads/2022/03/php-object-to-array-convert-using-json-decode.jpg" width="230" height="194" title="" alt="" /></div><div><div class="modified-on" readability="7.1666666666667"> by <a href="https://phppot.com/about/">Vincy</a>. Last modified on September 15th, 2021.</div>
<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>
<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>
<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>
<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>
<div class="post-section-highlight" readability="37">
<h2>Quick example</h2>
<p class="code-heading">PHP object to array conversion in a line using json_decode</p>
<pre class="prettyprint"><code class="language-php">
&lt;?php
$object = new StdClass();
$object-&gt;id = 5678;
$object-&gt;name = "William";
$object-&gt;department = "CSE";
$object-&gt;designation = "Engineer"; $result = json_encode($object);
// converts object $result to array
$output = json_decode($result, true); print "&lt;pre&gt;";
print_r($result);
?&gt;
</code></pre>
</div>
<h4>Output</h4>
<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>
<p><img 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>
<h2>Different ways of converting a PHP object to array</h2>
<p>When converting an object to array, the object property ‘name:value’ pairs will form an associative array.</p>
<p>If an object contains unassigned properties then it will return an array with numerical keys.</p>
<p>There are two ways to achieve a PHP object to array conversion.</p>
<ol>
<li><em>Typecasting</em> object into an array.</li>
<li><em>Encoding and decoding</em> object properties into an array of elements.</li>
</ol>
<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>
<p>This article includes examples of using both of the above methods to perform the object to array conversion.</p>
<h2>PHP object to array using typecasting</h2>
<p>This is an alternate method to convert an object type into an array. The below program uses the same input object.</p>
<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>
<p>The PHP typecasting syntax is shown below. It prepends the target data type enclosed with parenthesis.</p>
<pre class="prettyprint"><code class="language-php">
$output = (target-data-type) $input
</code></pre>
<p class="code-heading">type-casting-to-convert-object-to-array.php</p>
<pre class="prettyprint"><code class="language-php">
&lt;?php
$object = new StdClass();
$object-&gt;id = 5678;
$object-&gt;name = "William";
$object-&gt;department = "CSE";
$object-&gt;destination = "Engineer"; print"&lt;pre&gt;";
print_r( (array) $object );
?&gt;
</code></pre>
<h2>Recursive object to array conversion</h2>
<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>
<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>
<p class="code-heading">converting-recursive-object-to-array.php</p>
<pre class="prettyprint"><code class="language-php">
&lt;?php
$object = new StdClass();
$object-&gt;id = 5678;
$object-&gt;name = "William"; $object-&gt;address = new stdClass();
$object-&gt;address-&gt;email = "[email protected]"; $object-&gt;address-&gt;billing = new stdClass();
$object-&gt;address-&gt;billing-&gt;zipcode = 9950; $object-&gt;address-&gt;shipping = new stdClass();
$object-&gt;address-&gt;shipping-&gt;zipcode = 1234; $object-&gt;address-&gt;state = "South Carolina";
$object-&gt;address-&gt;city = "Columbia";
$object-&gt;address-&gt;country = "US"; function objectToArray($object)
{ foreach ($object as $k =&gt; $obj) { if (is_object($obj)) { $object-&gt;$k = objectToArray($obj); } else { $object-&gt;$k = $obj; } } return (array) $object;
} $result = objectToArray($object); print "&lt;pre&gt;";
print_r($result);
?&gt;
</code></pre>
<p>This is the output of the recursive PHP object to the array conversion program above.</p>
<p><img 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/20...11x300.jpg 211w" sizes="(max-width: 300px) 100vw, 300px"></p>
<h2>Convert PHP class object into array</h2>
<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>
<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>
<p class="code-heading">convert-class-object-into-array.php</p>
<pre class="prettyprint"><code class="language-php">
&lt;?php
class student
{ 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; }
} $student = new student("5678", "William", "South Carolina", "Columbia", "US");
$result = json_encode($student);
$output = json_decode($result, true);
print "&lt;pre&gt;";
print_r($output);
?&gt;
</code></pre>
<h2>Check is_object() before conversion</h2>
<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>
<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>
<p class="code-heading">checking-object-before-conversion.php</p>
<pre class="prettyprint"><code class="language-php">
&lt;?php class student
{ 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; }
}
$student= new student("5678", "William", "South Carolina", "Columbia", "US"); print "&lt;pre&gt;";
if (is_object($student)) { echo "Input Object:" . '&lt;br&gt;'; $result = json_encode($student); print_r($result); $studentArray = json_decode($result, true);
} if(!empty($studentArray) &amp;&amp; is_array($studentArray)) { echo "&lt;br&gt;&lt;br&gt;Output Array:" . '&lt;br&gt;'; print_r($studentArray);
}
?&gt;
</code></pre>
<h2>Convert Private, Protected object of a class</h2>
<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>
<p>It uses both the typecasting and decoding methods to convert the object into an array.</p>
<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>
<p class="code-heading">converting-private-protected-object.php</p>
<pre class="prettyprint"><code class="language-php">
&lt;?php
class Student
{ public $name; private $id; protected $email; public function __construct() { $this-&gt;name ="William"; $this-&gt;id = 5678; $this-&gt;email = "[email protected]"; }
} print "&lt;pre&gt;";
$student = new Student;
$result = json_encode($student);
$output1 = json_decode($result, true);
print "&lt;br/&gt;Using JSON decode:&lt;br/&gt;";
print_r($output1); $output2 = new Student;
print "&lt;br/&gt;&lt;br/&gt;Using Type casting:&lt;br/&gt;";
print_r( (array) $output2 );
?&gt;
</code></pre>
<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>
<p><img 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>
<h2>Accessing object properties with numeric keys</h2>
<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>
<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’t have a name.</p>
<p>The below code shows how to access objects with numeric keys. The key is enclosed by curly brackets to get the value.</p>
<p class="code-heading">problem-with-numerical-keys.php</p>
<pre class="prettyprint"><code class="language-php">
&lt;?php
$inputArray = array( 'name' =&gt; 'William', 'email' =&gt; '[email protected]', 'phone' =&gt; '12345678', 'REG5678'
); $student = (object) array( 'name' =&gt; 'William', 'email' =&gt; '[email protected]', 'phone' =&gt; '12345678', 'REG5678'
);
echo '&lt;pre&gt;' . print_r($student, true) . '&lt;/pre&gt;';
echo '&lt;br /&gt;' . $student-&gt;name;
echo '&lt;br /&gt;' . $student-&gt;email;
echo '&lt;br /&gt;' . $student-&gt;phone;
echo '&lt;br /&gt;' . $student-&gt;{0};
?&gt;
</code></pre>
<h2>Conclusion</h2>
<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>
<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>
<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>
<p> <!-- #comments --> </p>
<div class="related-articles">
<h2>Popular Articles</h2>
</p></div>
<p> <a href="https://phppot.com/php/php-object-to-array/#top" class="top">↑ Back to Top</a> </p>
</div>


https://www.sickgaming.net/blog/2021/09/...on-decode/
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016