Michael Ecklund Michael Ecklund - 5 months ago 7
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:

$category->term_id
$category->name
$category->slug
$category->term_group
$category->term_taxonomy_id
$category->taxonomy
$category->description
$category->parent
$category->count
$category->cat_ID
$category->category_count
$category->category_description
$category->cat_name
$category->category_nicename
$category->category_parent

Answer

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);

outputs:

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.