douqiang5933 2014-10-21 12:35
浏览 14

uasort排序所有数组,但我需要一个属性

this is problem bellow

$array[] = [
    'priority' => 0,
    'name' => 'a'
];
$array[] = [
    'priority' => 0,
    'name' => 'b'
];
$array[] = [
    'priority' => 10,
    'name' => 'c'
];
$array[] = [
    'priority' => 0,
    'name' => 'b'
];

function sortByPriority($a, $b){
    if ($a['priority'] == $b['priority']) {
        return 0;
    }
    return ($a['priority'] < $b['priority']) ? -1 : 1;
}
var_dump($array);
uasort($array, 'sortByPriority');
var_dump($array);

i expected that only 3rd element will be last, but element with name = 'a' now in 3rd position. why? it must be on 1st place!

UPD: i expected ordering (a,b,b,c) but i see on screen b,b,a,c

  • 写回答

1条回答 默认 最新

  • douxi3085 2014-10-22 04:16
    关注

    ryan-vincent give me a solution link, thank you

    SOLUTION

    UPDATE

    better solution use a http://en.wikipedia.org/wiki/Schwartzian_transform

    //decorate
    array_walk( $array,create_function('&$v, $k', '$v = [$v[\'priority\'], $k, $v];'));
    //sort
    sort($array);
    //undecorate
    array_walk( $array, create_function('&$v, $k', '$v = $v[2];'));
    
    评论

报告相同问题?