Home  >  Article  >  Backend Development  >  求教,数组排序解决思路

求教,数组排序解决思路

WBOY
WBOYOriginal
2016-06-13 13:44:52743browse

求教,数组排序
有一数组, 想要根b1和a进行二次排序,当b1不同时,按b1正序排列,当b1相同时,按a正序排列。要求效率要高。

PHP code
<!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

-->
array(
    [0] = array(
        ['a'] = 323,
        ['b'] = array(
            ['b1'] = 1
            )
        )    
    [1] = array(
        ['a'] = 234,
        ['b'] = array(
            ['b1'] = 1
            )
        )
    [2] = array(
        ['a'] = 135,
        ['b'] = array(
            ['b1'] = 2
            )
        )
)



------解决方案--------------------
这意思?
PHP code
<?php function cmp($a,$b){
    return $a['b']['b1'] == $b['b']['b1']?($a['a'] - $b['a']):($a['b']['b1'] - $b['b']['b1']);
}

$array = array(0=>array('a'=>323,'b'=>array('b1'=>1)),
               1=>array('a'=>324,'b'=>array('b1'=>1)),
               2=>array('a'=>135,'b'=>array('b1'=>2)),
);

usort($array,'cmp');
var_export($array);
<br><font color="#e78608">------解决方案--------------------</font><br>
探讨
这意思?

PHP code
function cmp($a,$b){
return $a['b']['b1'] == $b['b']['b1']?($a['a'] - $b['a']):($a['b']['b1'] - $b['b']['b1']);
}

$array = array(0=>array('a'=>323,'b'=>array('b1'=>1)……
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn