0

So this function works great for sorting array or object by 1 value

            function sort( $a, $b )
            { 
              if(  $a['1'] ==  $b['1'] ){ return 0 ; } 
              return ($a['1'] < $b['1']) ? -1 : 1;
            }
            usort($myArray,'sort');  

But I would like it to sort by value 1 primary and by value 2 second, if this is possible with this function, or is it only doable with a custom function?

  • 1
    you should use arraymulti_sort() or array_orderby(). Further reading: https://stackoverflow.com/questions/4582649/php-sort-array-by-two-field-values – Ofir Baruch Nov 02 '17 at 09:18
  • Thanks, I already found a solution, just a question, is arraymulti_sort() less demanding then usort? –  Nov 02 '17 at 09:21
  • that function **is** a custom function. No reason you can't customize it more. – apokryfos Nov 02 '17 at 09:30

2 Answers2

1

Sure, it's possible. To add an second sorting expression, you should extend the equal case $a['1'] == $b['1'].

You should also notice, you don't have to return exactly -1 or 1 - you could use any negative/positive number. So your sorter could be written as the following

usort(function($a, $b) { 
    if($a['1'] == $b['1']) {
        return $a['2'] - $b['2'];
    } 
    return $a['1'] - $b['1'];
}, 'sort');  
Philipp
  • 15,377
  • 4
  • 35
  • 52
0

I used this function. It is probably not the most efficient one, but for now it works.

            function comp($a, $b) {
                if ($a['1'] == $b['1']) {
                    return ($a['2'] < $b['2']) ? -1 : 1;
                }
                return strcmp($a['1'], $b['1']);
            }

            usort($arr, 'comp');