PHP数组状态多端口


PHP Array Multisort on Status

我正在尝试根据用户状态对数据库阵列进行多重排序。状态为1的位于阵列的顶部,状态为0的位于阵列底部。我以为我已经让它工作了,但今天由于向DB添加了新行,它就停止了。

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
)

正如我在另一个答案的注释中所提到的,将数组拆分为活动/非活动数组可能是比排序更好的解决方案。

$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);

uasort期望回调在$a应高于$b时返回正整数,在$b应高于$a时返回负整数,或者如果它们相等则返回0。

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

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

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