Home >Backend Development >PHP Tutorial >How to sort by key value in array in php

How to sort by key value in array in php

WBOY
WBOYOriginal
2016-07-29 09:09:091282browse
<code><?php
$array = array(
    array('name'=>'aa','price'=>1050),
    array('name'=>'bb','price'=>4300),
    array('name'=>'cc','price'=>3100),
    array('name'=>'dd','price'=>4900),
    array('name'=>'ee','price'=>960),
    array('name'=>'ff','price'=>6299),
    array('name'=>'gg','price'=>1200)
);
function arr_sort($array,$key,$order="asc"){ //asc是升序 desc是降序
    $arr_nums=$arr=array();
    foreach($array as $k=>$v){
        $arr_nums[$k]=$v[$key];
    }
    if($order=='asc'){
        asort($arr_nums);
    }else{
        arsort($arr_nums);
    }
    foreach($arr_nums as $k=>$v){
        $arr[$k]=$array[$k];
    }
    print_r($arr);
}
arr_sort($array,'price');
</code>

The above introduces how PHP sorts according to the key values ​​in the array, including the relevant content. I hope it will be helpful to friends who are interested in PHP tutorials.

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