php*_*00b 4 php sorting object
试图根据(1)深度和(2)权重对这个对象数组进行排序,并且我不确定如何修改我用来包含这个其他级别的函数...
我正在使用这个功能:
function cmp( $a, $b ) {
if( $a->weight == $b->weight ){ return 0 ; }
return ($a->weight < $b->weight) ? -1 : 1;
}
Run Code Online (Sandbox Code Playgroud)
然后这样做:
$menu = get_tree(4, $tid, -1, 2);
usort($menu, 'cmp');
Run Code Online (Sandbox Code Playgroud)
这将根据重量准确地对数组进行排序,但我需要添加另一级别的排序.因此,首先根据深度对数组进行排序,然后按重量进行排序.
所以,如果原始数组看起来像这样:
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
)
Run Code Online (Sandbox Code Playgroud)
我可以先按深度排序,然后按重量排序,以便结果如下所示:
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] => 0
[depth] => 1
)
Run Code Online (Sandbox Code Playgroud)
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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3164 次 |
| 最近记录: |