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

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

You need to sort your data twice, once by name and once by count value. I would suggest to use usort() and implement two custom compare methods:

<?php

  function cmpName($a, $b) {
    return strnatcmp($a['Name'], $b['Name']);
  }

  function cmpCountValue($a, $b) {
    if ($a['CountValue'] == 0)
      return 1;
    if ($b['CountValue'] == 0)
      return -1;
    return cmpName($a, $b);
  }

 $a[0]['Name'] = 'Bob';
 $a[0]['CountValue'] = 0;

 $a[1]['Name'] = 'Christal';
 $a[1]['CountValue'] = 42;

 $a[2]['Name'] = 'Alice';
 $a[2]['CountValue'] = 23;

 $a[3]['Name'] = 'Jack';
 $a[3]['CountValue'] = 1;

 $a[4]['Name'] = 'Alex';
 $a[4]['CountValue'] = 58;

  usort($a, "cmpName");
  usort($a, "cmpCountValue");

  foreach ($a as $item) {
    echo $item['Name'] . ": " . $item['CountValue'] . "<br />";
  }

?>

The output is:

Alex: 58
Alice: 23
Christal: 42
Jack: 1
Bob: 0

Online demo: See here