0

我正在尝试根据用户状态对数据库数组进行多重排序。Status = 1 的排在顶部,Status = 0 的排在阵列的底部。我以为我让它工作了,但它今天刚刚停止,向数据库中添加了新行。

uasort($ven, function ($a, $b) { return $a['v_status'] == '1' ? false : true; });

这是一个来自 MySQL 的简单数据库数组:

Array (
 [0] => array(
   [name] => '',
   [v_status] => 0
 [1] => array(
   [name] => '',
   [v_status] => 1
)
4

2 回答 2

1

正如对我的其他答案的评论中提到的,将数组拆分为活动/非活动数组可能是比排序更好的解决方案。

$items = array(
    array('name' => 'active1', 'active' => '1'),
    array('name' => 'inactive1', 'active' => '0'),
    array('name' => 'active2', 'active' => '1'),
    array('name' => 'inactive2', 'active' => '0'),
    array('name' => 'inactive3', 'active' => '0'),
    array('name' => 'active3', 'active' => '1'),
    array('name' => 'inactive4', 'active' => '0'),
);

$active = array_filter($items, function($item){ return $item['active'] == '1'; });
echo '<pre>' . print_r($active,true);

// You could filter again here, not sure which would be quicker, 
// but my guess would be the array_diff method (which also ensures
// that no items get filtered out by both filters)
$inactive = array_diff_key($items, $active);
echo '<pre>' . print_r($inactive,true);
于 2013-09-03T09:13:25.350 回答
0

如果 $a 应该高于 $b,则 uasort 期望回调返回一个正整数,如果 $b 应该高于 $a,则返回一个负整数,如果它们相等,则返回 0。

这就是为什么尽管只有 2 个选项,但 Jon 的建议return $b['v_status'] - $a['v_status'];是正确的。

在您的情况下,如果在排序 $a[v_status] = 0 和 $b[v_status] = 1 期间的某个时刻,该函数会查看 $a[v_status],返回 false,这等于 0 和算法(我认为快速排序) 将它们视为平等,因此将它们保留在当前顺序中。

请参阅PHP: usort以供参考,它需要类似的回调。

于 2013-08-28T23:42:13.090 回答