Reputation: 29
I have an array of objects that I need to sort by parent (from lowest to highest).
Here's the structure of the array:
[{
"term_id": 9,
"name": "pve",
"slug": "pve",
"term_group": 0,
"term_taxonomy_id": 9,
"taxonomy": "post_tag",
"description": "pve guides",
"parent": 15,
"count": 0,
"filter": "raw"
}, {
"term_id": 8,
"name": "pvp",
"slug": "pvp",
"term_group": 0,
"term_taxonomy_id": 8,
"taxonomy": "post_tag",
"description": "pvp guides",
"parent": 15,
"count": 2,
"filter": "raw"
}, {
"term_id": 11,
"name": "greataxe",
"slug": "greataxe",
"term_group": 0,
"term_taxonomy_id": 11,
"taxonomy": "post_tag",
"description": "greataxe guides",
"parent": 14,
"count": 1,
"filter": "raw"
}, {
"term_id": 12,
"name": "musket",
"slug": "musket",
"term_group": 0,
"term_taxonomy_id": 12,
"taxonomy": "post_tag",
"description": "musket guides",
"parent": 14,
"count": 0,
"filter": "raw"
}, {
"term_id": 13,
"name": "spear",
"slug": "spear",
"term_group": 0,
"term_taxonomy_id": 13,
"taxonomy": "post_tag",
"description": "",
"parent": 14,
"count": 1,
"filter": "raw"
}, {
"term_id": 10,
"name": "sword",
"slug": "sword",
"term_group": 0,
"term_taxonomy_id": 10,
"taxonomy": "post_tag",
"description": "sword guides",
"parent": 14,
"count": 0,
"filter": "raw"
}, {
"term_id": 15,
"name": "Play Type",
"slug": "playtype",
"term_group": 0,
"term_taxonomy_id": 15,
"taxonomy": "post_tag",
"description": "",
"parent": 0,
"count": 0,
"filter": "raw"
}, {
"term_id": 14,
"name": "Weapons",
"slug": "weapons",
"term_group": 0,
"term_taxonomy_id": 14,
"taxonomy": "post_tag",
"description": "",
"parent": 0,
"count": 0,
"filter": "raw"
}]
I tried sorting it with the follow
$new_array = usort($tags, function($a, $b) {
return $b->parent - $a->parent;
})
My desired outcome would be an array which reorganizes the array by parent (so all the objects with a parent of 0 would be on the top). Instead, I'm getting a value of true returned.
Any help would be appreciated.
Upvotes: 2
Views: 538
Reputation: 511
usort (http://php.net/usort) performs the sort directly on the provided array. The return value just returns boolean telling if the sorting succeeded.
Furthermore,
The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.
therefore you should provide $a->parent - $b->parent
to get the items sorted in an ascending order.
usort($tags, function($a, $b) {
return $a->parent - $b->parent;
});
$new_array = $tags; // The $tags is now sorted
Upvotes: 2