gpt4 book ai didi

php - 按对象 ID 在 PHP 中对数组进行排序

转载 作者:行者123 更新时间:2023-12-04 10:50:15 24 4
gpt4 key购买 nike

我有一组需要按父级排序的对象(从最低到最高)。

这是数组的结构:

[{
"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"
}]

我尝试使用以下方法对其进行排序
$new_array = usort($tags, function($a, $b) {
return $b->parent - $a->parent;
})

我想要的结果是一个按父级重新组织数组的数组(因此父级为 0 的所有对象都在顶部)。相反,我得到了一个 true 返回值。

任何帮助,将不胜感激。

最佳答案

usort ( http://php.net/usort ) 直接对提供的数组执行排序。返回值只返回 bool 值,告诉排序是否成功。

此外,

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.



因此您应该提供 $a->parent - $b->parent以升序对项目进行排序。

usort($tags, function($a, $b) {
return $a->parent - $b->parent;
});
$new_array = $tags; // The $tags is now sorted

关于php - 按对象 ID 在 PHP 中对数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59514548/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com