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
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.
as simple as
$array = (array)$object;
http://www.php.net/manual/en/language.types.array.php#language.types.array.casting
To convert an object to array you can use get_object_vars()
(PHP manual):
$categoryVars = get_object_vars($category)
To convert the entire object and all it's properties to arrays, you can use this clunky function I've had kicking around for a while:
function object_to_array($object)
{
if (is_array($object) OR is_object($object))
{
$result = array();
foreach($object as $key => $value)
{
$result[$key] = object_to_array($value);
}
return $result;
}
return $object;
}
Demo: http://codepad.org/Tr8rktjN
But for your example, with that data, you should be able to just cast to array as others have already said.
$array = (array) $object;
To add to @galen
<?php
$categories = get_categories();
$array = (array)$categories;
?>
A less clunky way might be:
function objectToArray($object)
{
if(!is_object( $object ) && !is_array( $object ))
{
return $object;
}
if(is_object($object) )
{
$object = get_object_vars( $object );
}
return array_map('objectToArray', $object );
}
(Sourced from http://www.sitepoint.com/forums/showthread.php?438748-convert-object-to-array) Note, if you'd like this as a method in a class, change the last line to:
return array_map(array($this, __FUNCTION__), $object );
$array = json_decode(json_encode($object), true);