gpt4 book ai didi

php 按两个标准对对象进行排序?

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:02:04 25 4
gpt4 key购买 nike

尝试根据 (1) 深度和 (2) 权重对这个对象数组进行排序,但不确定如何修改我正在使用的函数以包含其他级别...

我正在使用这个函数:

function cmp( $a, $b ) {
if( $a->weight == $b->weight ){
return 0 ;
}
return ($a->weight < $b->weight) ? -1 : 1;
}

然后这样做:

$menu = get_tree(4, $tid, -1, 2);
usort($menu, 'cmp');

这将根据权重对数组进行准确排序,但我需要添加另一个级别的排序。这样数组先按深度排序,再按权重排序。

因此,如果原始数组如下所示:

    Array
(
[0] => stdClass Object
(
[tid] => 24
[name] => Sample
[weight] => 3
[depth] => 0
)

[1] => stdClass Object
(
[tid] => 66
[name] => Sample Subcategory
[weight] => 0
[depth] => 1
)

[2] => stdClass Object
(
[tid] => 67
[name] => Another Example
[weight] => 1
[depth] => 0
)

[3] => stdClass Object
(
[tid] => 68
[name] => Subcategory for Another Example
[weight] => 1
[depth] => 1
)

[4] => stdClass Object
(
[tid] => 22
[name] => A third example master category
[weight] => 0
[depth] => 0
)

我可以先按深度排序,然后按权重排序,结果如下所示:

Array
(
[0] => stdClass Object
(
[tid] => 22
[name] => A third example master category
[weight] => 0
[depth] => 0
)

[1] => stdClass Object
(
[tid] => 67
[name] => Another Example
[weight] => 1
[depth] => 0
)

[2] => stdClass Object
(
[tid] => 24
[name] => Sample
[weight] => 3
[depth] => 0
)

[3] => stdClass Object
(
[tid] => 66
[name] => Sample Subcategory
[weight] => 0
[depth] => 1
)

[4] => stdClass Object
(
[tid] => 68
[name] => Subcategory for Another Example
[weight] => 1
[depth] => 1
)

最佳答案

function cmp( $a, $b )
{
if ($a->depth == $b->depth)
{
if($a->weight == $b->weight) return 0 ;
return ($a->weight < $b->weight) ? -1 : 1;
}
else
return ($a->depth < $b->depth) ? -1 : 1;
}

关于php 按两个标准对对象进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2368027/

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