How to sort an array of associative arrays by value of a given key in PHP?

前端 未结 19 1824
清酒与你
清酒与你 2020-11-21 23:34

Given this array:

$inventory = array(

   array(\"type\"=>\"fruit\", \"price\"=>3.50),
   array(\"type\"=>\"milk\", \"price\"=>2.90),
   array(\"         


        
19条回答
  •  无人及你
    2020-11-22 00:20

    From Sort an array of associative arrays by value of given key in php:

    by using usort (http://php.net/usort) , we can sort an array in ascending and descending order. just we need to create a function and pass it as parameter in usort. As per below example used greater than for ascending order if we passed less than condition then it's sort in descending order. Example :

    $array = array(
      array('price'=>'1000.50','product'=>'test1'),
      array('price'=>'8800.50','product'=>'test2'),
      array('price'=>'200.0','product'=>'test3')
    );
    
    function cmp($a, $b) {
      return $a['price'] > $b['price'];
    }
    
    usort($array, "cmp");
    print_r($array);
    

    Output:

    Array
     (
        [0] => Array
            (
                [price] => 200.0
                [product] => test3
            )
    
        [1] => Array
            (
                [price] => 1000.50
                [product] => test1
            )
    
        [2] => Array
            (
                [price] => 8800.50
                [product] => test2
            )
      )
    

提交回复
热议问题