Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 902
Michael Ecklund Avatar asked Nov 27 '22 18:11

Michael Ecklund


2 Answers

$array = json_decode(json_encode($object), true);
like image 181
Farhod Avatar answered Nov 30 '22 07:11

Farhod


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.

like image 22
Andy Avatar answered Nov 30 '22 06:11

Andy