0

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!

2
  • 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? Commented Jul 21, 2010 at 19:55
  • possible duplicate of How do I sort a multi-dimensional array by value? Commented Jul 21, 2010 at 19:58

3 Answers 3

4
<?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);  
?>
Sign up to request clarification or add additional context in comments.

1 Comment

backticks are generally best for $small_bits, whereas indenting with 4 spaces is best for code blocks. Edited to make things look prettier :)
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');

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.