尝试根据(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] => 0
[depth] => 1
)
答案 0 :(得分:9)
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;
}
答案 1 :(得分:2)
比较数字时,你可以简单地减去它们
function cmp($a, $b) {
$d = $a->depth - $b->depth;
return $d ? $d : $a->weight - $b->weight;
}
答案 2 :(得分:-1)
自2010年以来,PHP进行了重大改进。对于此任务,可以使用PHP7“太空飞船运算符”或“三向比较运算符”在usort()
调用中进行单行比较。
代码:(Demo)
usort($menu, function($a, $b) {
return [$a->depth, $a->weight] <=> [$b->depth, $b->weight];
});
输出:
array (
0 =>
(object) array(
'tid' => 22,
'name' => 'A third example master category',
'weight' => 0,
'depth' => 0,
),
1 =>
(object) array(
'tid' => 67,
'name' => 'Another Example',
'weight' => 1,
'depth' => 0,
),
2 =>
(object) array(
'tid' => 24,
'name' => 'Sample',
'weight' => 3,
'depth' => 0,
),
3 =>
(object) array(
'tid' => 66,
'name' => 'Sample Subcategory',
'weight' => 0,
'depth' => 1,
),
4 =>
(object) array(
'tid' => 68,
'name' => 'Subcategory for Another Example',
'weight' => 1,
'depth' => 1,
),
)
在左侧数组中写入$a
属性,在右侧数组中$b
属性将对ASC进行排序;反转这些位置以使用DESC定向排序。
扩展名:如果要按以下顺序排序:$weight
DESC,然后$name
ASC,然后$depth
DESC,则编写比较条件数组,如下所示:
[$b->weight, $a->name, $b->depth] <=> [$a->weight, $b->name, $a->depth]
从PHP7.2开始,可以使用另一种技术:array_multisort()
和多次调用array_column()
。在7.2之前,array_column()
不能用于对象。)
代码:(Demo)
array_multisort(array_column($menu, 'depth'), array_column($menu, 'weight'), $menu);
要反映我之前的“扩展”中的条件,语法会更长一些,因为每一列都需要自己的array_column()
调用,并且需要表达排序方向。
array_multisort(array_column($menu, 'weight'), SORT_DESC, array_column($menu, 'name'), array_column($menu, 'depth'), SORT_DESC, $menu);