dreamact3026 2018-01-31 13:31
浏览 203
已采纳

PHP - 按字母排序数组,但将具有0值的数组移到最后

I have those 2 functions and I need to build a new one that will

  • first sort the array by Name
  • and then move the values with ['countValue'] = 0 to the end

    public function sortOptionsByName($a, $b)
    {
        $x = trim($a['label']);
        $y = trim($b['label']);
    
        if ($x == '') return 1;
        if ($y == '') return -1;
    
        if (is_numeric($x) && is_numeric($y)){
            if ($x == $y)
                return 0;
            return ($x > $y ? 1 : -1);
        }
        else {
            return strcasecmp($x, $y);
        }
    }
    
    
    public function sortOptionsByCounts($a, $b)
    {
        if ($a['countValue'] == $b['countValue']) {
            return 0;
        }
    
        return ($a['countValue'] < $b['countValue'] ? 1 : -1);
    }
    

Something like...

public function sortOptionsByCountsAndByName($a, $b)
{
    if ($a['countValue'] == 0 &&  $b['countValue'] == 0) {
        return -2
    }
    else {
        $this->sortOptionsByName($a, $b)
    }        
}
  • 写回答

2条回答 默认 最新

  • du8794 2018-01-31 14:26
    关注

    First compare values with zero. PHP casts boolean to integer, so you can just subtract to get -1, 0 , 1. And then compare another value when thw 1st comparing returns 0

    public function sortOptionsByCountsAndByName($a, $b)
    {
        $res = ($a['countValue'] == 0) - ($b['countValue'] == 0);
        return ($res ? $res : $this->sortOptionsByName($a, $b));
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?