Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
recursively cast a PHP object to array
<?php
/*
This function saved my life.
found on: http://www.sitepoint.com/forums//showthread.php?t=438748
by: crvandyke
It takes an object, and when all else if/else/recursive functions fail to convert the object into an associative array, this one goes for the kill. Who would'a thunk it?!
*/
$array = json_decode(json_encode($object), true);
@dsteplight

This comment has been minimized.

Copy link

dsteplight commented Dec 2, 2014

Do you know how many times I've had to do this over the past few years and it was ugly. This is definitely a life saver!

@CodeKJ

This comment has been minimized.

Copy link

CodeKJ commented Feb 4, 2016

Exactly what I was looking for. Give this man a beer.

@mtanneb

This comment has been minimized.

Copy link

mtanneb commented Mar 11, 2016

Awesome!

@TwanoO67

This comment has been minimized.

Copy link

TwanoO67 commented May 11, 2016

Just tried over some nested objects/array and it didn't work.
But this does (not as elegant, but more effective):

`private function object_to_array($obj) {
if(is_object($obj)) $obj = (array) $this->dismount($obj);
if(is_array($obj)) {
$new = array();
foreach($obj as $key => $val) {
$new[$key] = $this->object_to_array($val);
}
}
else $new = $obj;
return $new;
}

//permet de changer les private en public, pour un meuilleur conversion des object en array
private function dismount($object) {
$reflectionClass = new ReflectionClass(get_class($object));
$array = array();
foreach ($reflectionClass->getProperties() as $property) {
$property->setAccessible(true);
$array[$property->getName()] = $property->getValue($object);
$property->setAccessible(false);
}
return $array;
}`

@mdeboer

This comment has been minimized.

Copy link

mdeboer commented Aug 7, 2016

@TwanoO67 I had the same issue when converting an array to object using the code below. It only converted the outer most array to object and not the nested arrays.

$object = json_decode(json_encode($array), false);

I solved this by using:

$object = json_decode(json_encode($array, JSON_FORCE_OBJECT), false);

I'm pretty sure the solution would be similar when converting from object to array.

@sajjad-dehghani

This comment has been minimized.

Copy link

sajjad-dehghani commented Aug 18, 2016

Awesome!

@ChristopherDosin

This comment has been minimized.

Copy link

ChristopherDosin commented May 3, 2017

Mine too! 🥇

@inonbaguio

This comment has been minimized.

Copy link

inonbaguio commented Jul 25, 2017

This will not be be applicable if the properties of the object you are trying to convert are declared as private

@christoferd

This comment has been minimized.

Copy link

christoferd commented Oct 14, 2017

@mdeboer Thank you
That worked for me too

$object = json_decode(json_encode($array, JSON_FORCE_OBJECT), false);
@bonatoc

This comment has been minimized.

Copy link

bonatoc commented Jan 25, 2018

Thanks!
Works fine on PHP 5.3.29

@arnisjuraga

This comment has been minimized.

Copy link

arnisjuraga commented Jan 30, 2018

Nice!

@fendiseptiawan0709

This comment has been minimized.

Copy link

fendiseptiawan0709 commented Jul 21, 2018

@victorbstan thanks man.

@anver

This comment has been minimized.

Copy link

anver commented Jul 29, 2018

@mdeboer Thank you
Saved ton of my time

@quasi635

This comment has been minimized.

Copy link

quasi635 commented Aug 8, 2018

I love the simplicity. Thank you!

@desjob

This comment has been minimized.

Copy link

desjob commented Oct 5, 2018

am i the only one here that minds the "wasted" cycles of json encoding + decoding?

@Okipa

This comment has been minimized.

Copy link

Okipa commented Dec 10, 2018

In case of complex objects, you will have serious performance issues with json_decode(json_encode())

@yoshkinawa

This comment has been minimized.

Copy link

yoshkinawa commented Jun 16, 2019

Use this function to access also private and protected arguments

function obj2arr( $obj, $nestLevel = 0 ) {

// limit nesting level (for performance and not to go over the maximum)
if ( $nestLevel > 15 ) return;

// if current member is an object - turn it to an array
if( is_object( $obj ) ) $obj = (array) $obj;

// if current member is an array - recursively call this function to each of his children
if( is_array( $obj ) ) {

	$return = [];

	foreach( $obj as $key => $val ) {

		// correct private and protected key names
		$aux = explode ( "\0", $key );
		$newkey = $aux[ count( $aux ) - 1 ];
		$return[ $newkey ] = obj2arr( $val, $nestLevel + 1 );

	}

} else $return = $obj;

// return transformed object
return $return;

}

@scmrus

This comment has been minimized.

Copy link

scmrus commented Aug 29, 2019

Use ArrayObject class and cast it to array (or use ArrayObject::getArrayCopy() instead). It's much much faster.

php > $x = [1, (object) ['x'=>'y'], 3];
php > var_dump($x);
array(3) {
  [0] =>
  int(1)
  [1] =>
  class stdClass#1 (1) {
    public $x =>
    string(1) "y"
  }
  [2] =>
  int(3)
}
php > var_dump((new ArrayObject($x))->getArrayCopy());
array(3) {
  [0] =>
  int(1)
  [1] =>
  class stdClass#1 (1) {
    public $x =>
    string(1) "y"
  }
  [2] =>
  int(3)
}
@c01nd01r

This comment has been minimized.

Copy link

c01nd01r commented Sep 2, 2019

Use ArrayObject class and cast it to array (or use ArrayObject::getArrayCopy() instead). It's much much faster.

ArrayObject::getArrayCopy() return shallow copy of array.

@MAChitgarha

This comment has been minimized.

Copy link

MAChitgarha commented Sep 4, 2019

@scmrus and @c01nd01r
I actually understood this after trying it, but I forgot to remove the comment from here. Sorry.
BTW, a recursive function in PHP is faster than the JSON way.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.