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

前端 未结 19 1827
清酒与你
清酒与你 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:30

    //Just in one line custom function
    function cmp($a, $b)
    {
    return (float) $a['price'] < (float)$b['price'];
    }
    @uasort($inventory, "cmp");
    print_r($inventory);
    
    //result
    
    Array
    (
    [2] => Array
        (
            [type] => pork
            [price] => 5.43
        )
    
    [0] => Array
        (
            [type] => fruit
            [price] => 3.5
        )
    
    [1] => Array
        (
            [type] => milk
            [price] => 2.9
        )
    
    )
    

提交回复
热议问题