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

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

    Since your array elements are arrays themselves with string keys, your best bet is to define a custom comparison function. It's pretty quick and easy to do. Try this:

    function invenDescSort($item1,$item2)
    {
        if ($item1['price'] == $item2['price']) return 0;
        return ($item1['price'] < $item2['price']) ? 1 : -1;
    }
    usort($inventory,'invenDescSort');
    print_r($inventory);
    

    Produces the following:

    Array
    (
        [0] => Array
            (
                [type] => pork
                [price] => 5.43
            )
    
        [1] => Array
            (
                [type] => fruit
                [price] => 3.5
            )
    
        [2] => Array
            (
                [type] => milk
                [price] => 2.9
            )
    
    )
    

提交回复
热议问题