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
Release: 2016-07-29 09:09:09
Original
1290 people have browsed it
<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>
Copy after login

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.

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template