views:

30

answers:

3

I have an multi dimensional array:

$array[0] = array ( name => "Bob",
    position => "Chair",
    email => "[email protected]"
);
$array[1] = array ( name => "Al",
    position => "",
    email => "[email protected]"
);
//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!

A: 

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.

infamouse
+1  A: 

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
+2  A: 
<?php  
$array[0] = array ( name => "Bob", position => "Chair", email => "[email protected]");  
$array[1] = array ( name => "Al", position => "",email => "[email protected]");  
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);  
?>
Irwin
gosh, its hard formatting my php.
Irwin
@Irwin - backticks are generally best for `$small_bits`, whereas indenting with 4 spaces is best for code blocks. Edited to make things look prettier :)
Matchu
thanks @Matchu!
Irwin