Saturday, August 17, 2013

Objects to Array php

8/17/2013


Every PHP coders have come accross Arrays and stdClass Objects (belongs to PHP Predefined Classes). Sometimes it’s very useful convert Objects to Arrays and Arrays to Objects. This is easy if arrays and objects are one-dimensional, but might be little tricky if using multidimensional arrays and objects.



This post defines two simple function to convert
:multidimensional Objects to Arrays
:multidimensional Arrays to Objects


Function to Convert stdClass Objects to Multidimensional Arrays
Objects to Array php


<?php
/* 
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.in/
*/

 
 function objectToArray($d) {
  if (is_object($d)) {
   // Gets the properties of the given object
   // with get_object_vars function
   $d = get_object_vars($d);
  }
 
  if (is_array($d)) {
   /*
   * Return array converted to object
   * Using __FUNCTION__ (Magic constant)
   * for recursive call
   */
   return array_map(__FUNCTION__, $d);
  }
  else {
   // Return array
   return $d;
  }
 }
 
?>




Function to Convert Multidimensional Arrays to stdClass Objects
<?php
/* 
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.in/
*/

 
 function arrayToObject($d) {
  if (is_array($d)) {
   /*
   * Return array converted to object
   * Using __FUNCTION__ (Magic constant)
   * for recursive call
   */
   return (object) array_map(__FUNCTION__, $d);
  }
  else {
   // Return object
   return $d;
  }
 }

?>

Function usage

<?php
/* 
Online PHP Examples with Source Code
website: http://4evertutorials.blogspot.in/
*/


// Create new stdClass Object
 $init = new stdClass;
 
 // Add some test data
 $init->foo = "Test data";
 $init->bar = new stdClass;
 $init->bar->baaz = "Testing";
 $init->bar->fooz = new stdClass;
 $init->bar->fooz->baz = "Testing again";
 $init->foox = "Just test";
 
 // Convert array to object and then object back to array
 $array = objectToArray($init);
 $object = arrayToObject($array);
 
 // Print objects and array
 print_r($init);
 echo "\n";
 print_r($array);
 echo "\n";
 print_r($object);

?>

helpful? Share this

The Editorial Team of 4everTutorials consists of a group of PHP Professionals.

0 comments:

 

© 2014 4everTutorials. All rights resevered.

Back To Top