Home  >  Article  >  Backend Development  >  PHP中数组的分组排序实例_PHP教程

PHP中数组的分组排序实例_PHP教程

WBOY
WBOYOriginal
2016-07-13 10:29:09654browse

PHP的数组,数组中的内容大致如下:

复制代码 代码如下:

$list = array(
    array(2,3,5),
    array(2,5,24),
    array(3,8,6),
    array(3,2,10),
    array(4,7,20),
    array(4,1,15),
    array(6,4,10),
    array(7,9,20),
    );

为了方便表达,我把3列数字分别称为,ABC三列

需求:默认以A列排序为主,如果A列相同则以C列倒序排列相同的元素。B列其实没有参与排序,但是在实际运用中有用,所以我也写出来了。

方法一:

复制代码 代码如下:

$a = $c = array();
foreach($list as $val){
    $a[] = $val[0]; //a列
    $c[] = $val[2]; //c列
}
//安装a列升序,然后安装b列降序 , 类似sql,orderby a asc,b desc
array_multisort($a,SORT_ASC , $c, SORT_DESC, $list);
print_r($list);

方法二:
复制代码 代码如下:

for($j=0;$j    for($i=count($list)-1;$i>$j;$i--){
        if($list[$i][0] == $list[$i-1][0] && $list[$i][2] > $list[$i-1][2])
            list($list[$i],$list[$i-1]) = array($list[$i-1],$list[$i]);
    }
}

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/779000.htmlTechArticlePHP的数组,数组中的内容大致如下: 复制代码 代码如下: $list = array( array(2,3,5), array(2,5,24), array(3,8,6), array(3,2,10), array(4,7,20), array(4,1,15), a...
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