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条)

报告相同问题?

悬赏问题

  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题
  • ¥15 企业资源规划ERP沙盘模拟
  • ¥15 树莓派控制机械臂传输命令报错,显示摄像头不存在
  • ¥15 前端echarts坐标轴问题
  • ¥15 ad5933的I2C
  • ¥15 请问RTX4060的笔记本电脑可以训练yolov5模型吗?
  • ¥15 数学建模求思路及代码
  • ¥50 silvaco GaN HEMT有栅极场板的击穿电压仿真问题