0

I'm using a function called subval_sort to sort a multi-dimensional array.

function subval_sort($a,$subkey) {
  foreach($a as $k=>$v) {
    $b[$k] = strtolower($v[$subkey]);
  }
  asort($b);
  foreach($b as $key=>$val) {
    $c[] = $a[$key];
  }
  return $c;
}

$songs =  array(
    '1' => array('artist'=>'Bing Crosby', 'songname'=>'White Christmas'),
    '2' => array('artist'=>'Elvis Presley', 'songname'=>'White Christmas'),
    '3' => array('artist'=>'Abba', 'songname' =>'Waterloo')
);

$songs = subval_sort($songs,'songname'); 
print_r($songs);

Works fine. Now I want to sort by songname as first and artist as second. So: if two (or more) songname-values are the same I want to sort by artist. Like in SQL: ORDER BY songname, artist.

Do you have any ideas how to solve it?

Aleksei Matiushkin
  • 119,336
  • 10
  • 100
  • 160
Kristoffer
  • 1,984
  • 3
  • 14
  • 29

1 Answers1

1

You can use usort where you can define the custom comparison function

function cmp($a, $b)
{
    if(strcmp($a['songname'], $b['songname'])) {
        return strcmp($a['songname'], $b['songname']);
    }
    return strcmp($a["artist"], $b["artist"]);
}

implementation: usort($songs, "cmp");

Community
  • 1
  • 1
Fallen
  • 4,435
  • 2
  • 26
  • 46