douyan1972
2013-08-28 23:07 阅读 69
已采纳

PHP Array_multisort状态

I'm trying to multisort a DB array based on the users status. Those with Status = 1 go at the top, those with Status = 0 go at the bottom of the array. I thought I had it working but it just stopped today with the addition of new rows to the DB.

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

It's a simple DB array from MySQL:

Array (
 [0] => array(
   [name] => '',
   [v_status] => 0
 [1] => array(
   [name] => '',
   [v_status] => 1
)
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

2条回答 默认 最新

  • 已采纳
    dongpo1203 dongpo1203 2013-09-03 09:13

    As mentioned in comments to my other answer, splitting the array into active/inactive arrays could be a better solution than sorting.

    $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);
    
    点赞 评论 复制链接分享
  • dongqian0763 dongqian0763 2013-08-28 23:42

    uasort expects the callback to return a positive integer if $a should be above $b, a negative integer if $b should be above $a or 0 if they are equal.

    This is why despite there only being 2 options Jon's suggestion return $b['v_status'] - $a['v_status']; is correct.

    In your case if at some point during the sort $a[v_status] = 0 and $b[v_status] = 1 the function looks at $a[v_status], returns false, which equates to 0 and the algorithm (quick sort I think) treats them as equal and therefore leaves them in their current order.

    See PHP: usort for reference, which expects a similar callback.

    点赞 评论 复制链接分享

相关推荐