开发者

How to sort PHP multidimensional associative array with a selected key value

开发者 https://www.devze.com 2023-04-08 00:42 出处:网络
How to sort following php array with its \'zindex\' key value $array = array(\'the-1\'=> array(\'name\'=>\'lorem\',\'pos\'=>array(\'top\'=>\'90\',\'left\'=>\'80\'),\'zindex\'=&开发者_如

How to sort following php array with its 'zindex' key value

$array = array('the-1'=> array('name'=>'lorem','pos'=>array('top'=>'90','left'=>'80'),'zindex'=&开发者_如何学运维gt;2),
        'the-2'=> array('name'=>'ipsum','pos'=>array('top'=>'190','left'=>'180'),'zindex'=>1),
        'the-3'=> array('name'=>'lorem ipsum','pos'=>array('top'=>'20','left'=>'30'),'zindex'=>3)
        )

Is there any php function for getting the output as follows,

$array = array(
        'the-2'=> array('name'=>'ipsum','pos'=>array('top'=>'190','left'=>'180'),'zindex'=>1),
        'the-1'=> array('name'=>'lorem','pos'=>array('top'=>'90','left'=>'80'),'zindex'=>2),
        'the-3'=> array('name'=>'lorem ipsum','pos'=>array('top'=>'20','left'=>'30'),'zindex'=>3)
        )


usort($array, function($a, $b) {
    if ($a['name'] == $b['name']) {
        return 0;
    }
    return ($a['name'] < $b['name']) ? -1 : 1;
}); 

This should do the trick for you... It did for me ;)


usort($array,function($el1,$el2){
    return $el1-$el2;
});

Requires PHP5.3

if you need older versions' support replace anonymous function by usual one

0

精彩评论

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

关注公众号