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

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

    Was tested on 100 000 records: Time in seconds(calculated by funciton microtime). Only for unique values on sorting key positions.

    Solution of function of @Josh Davis: Spended time: 1.5768740177155

    Mine solution: Spended time: 0.094044923782349

    Solution:

    function SortByKeyValue($data, $sortKey, $sort_flags=SORT_ASC)
    {
        if (empty($data) or empty($sortKey)) return $data;
    
        $ordered = array();
        foreach ($data as $key => $value)
            $ordered[$value[$sortKey]] = $value;
    
        ksort($ordered, $sort_flags);
    
        return array_values($ordered); *// array_values() added for identical result with multisort*
    }
    

提交回复
热议问题