Michael Ecklund Michael Ecklund - 2 years ago 56
PHP Question

Convert an Object to an Array

I am working with WordPress and since I don't believe it is possible to sort object details, I was wondering how to go about converting my Object to an Array, so that sorting can be possible.

Any help or guidance would be greatly appreciated.

I am using the WP function get_categories();

The complete content of $category is:


Answer Source

If the object is not too complex (in terms of nesting) you can cast the class to an array:

$example = new StdClass();
$example->foo = 'bar';

var_dump((array) $example);


array(1) { ["foo"]=> string(3) "bar" } 

However this will only convert the base level. If you have nested objects such as

$example = new StdClass();
$example->foo = 'bar';
$example->bar = new StdClass();
$example->bar->blah = 'some value';

var_dump((array) $example);

Then only the base object will be cast to an array.

array(2) { 
  ["foo"]=> string(3) "bar" 
  ["bar"]=> object(stdClass)#2 (1) { 
    ["blah"]=> string(10) "some value" 

In order to go deeper, you would have to use recursion. There is a good example of an object to array conversion here.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download