0

I have an multi dimensional array:

$array[0] = array ( name => "Bob",
    position => "Chair",
    email => "bob@foo.bar"
);
$array[1] = array ( name => "Al",
    position => "",
    email => "al@foo.bar"
);
//etc..

I want to sort it so that those whose position != "" are first, then the rest alphabetically by name... I'm not very familiar w/ sorting multidimensional arrays, could someone help me? Thanks!

aslum
  • 11,774
  • 16
  • 49
  • 70
  • And in what order do you want the ones with no position to be in? For example, alphabetical by email/name or in their original order? – salathe Jul 21 '10 at 19:55
  • possible duplicate of [How do I sort a multi-dimensional array by value?](http://stackoverflow.com/questions/3281841/how-do-i-sort-a-multi-dimensional-array-by-value) – Wrikken Jul 21 '10 at 19:58

3 Answers3

4
<?php  
$array[0] = array ( name => "Bob", position => "Chair", email => "bob@foo.bar");  
$array[1] = array ( name => "Al", position => "",email => "al@foo.bar");  
print_r($array);  

$idxPos = array();  
for ($i=0;$i<count($array);$i++)
{  
    $idxPos[$i] = $array[$i]["position"]; 
}  
arsort($idxPos);  

$arrayNew = array();  
$sortedKeys = array_keys($idxPos);  
for($p=0;$p<count($idxPos);$p++)
{
$arrayNew[] = $array[$sortedKeys[$p]];
}
$array = $arrayNew;  

print_r("<br />");  
print_r($array);  
?>
Wistar
  • 3,770
  • 4
  • 45
  • 70
Irwin
  • 12,551
  • 11
  • 67
  • 97
  • backticks are generally best for `$small_bits`, whereas indenting with 4 spaces is best for code blocks. Edited to make things look prettier :) – Matchu Jul 21 '10 at 20:30
1

The usort function is probably your best bet for this:

usort($array, function($a, $b) {
    if (empty($a['position']) && !empty($b['position'])) {
        return 1; 
    }   
    else if (!empty($a['position']) && empty($b['position'])) {
        return -1;
    }   
    else {
        return strcmp($a['name'], $b['name']);
    }   
});

Anonymous functions were introduced in PHP 5.3.0. If you're using an earlier version you can just define a regular function instead:

function cmp($a, $b) {
    if (empty($a['position']) && !empty($b['position'])) {
        return 1; 
    }   
    else if (!empty($a['position']) && empty($b['position'])) {
        return -1;
    }   
    else {
        return strcmp($a['name'], $b['name']);
    }   
}

usort($array, 'cmp');
Daniel Egeberg
  • 8,359
  • 31
  • 44
0

You'll probably want to try usort so you can use a custom sorting function. In the sorting function you can check a["position"] vs b["position"] in the way you describe.

funwhilelost
  • 1,990
  • 17
  • 20