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

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

    I ended on this:

    function sort_array_of_array(&$array, $subfield)
    {
        $sortarray = array();
        foreach ($array as $key => $row)
        {
            $sortarray[$key] = $row[$subfield];
        }
    
        array_multisort($sortarray, SORT_ASC, $array);
    }
    

    Just call the function, passing the array and the name of the field of the second level array. Like:

    sort_array_of_array($inventory, 'price');
    

提交回复
热议问题