开发者

sorting part of a multidimensional array

开发者 https://www.devze.com 2023-01-08 12:51 出处:网络
I have an multi dimensional array: $array[0] = array ( name => \"Bob\", position => \"Chair\", email => \"bob@foo.bar\"

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, c开发者_高级运维ould someone help me? Thanks!


<?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);  
?>


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');


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号