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

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

    This function is re-usable:

    function usortarr(&$array, $key, $callback = 'strnatcasecmp') {
        uasort($array, function($a, $b) use($key, $callback) {
            return call_user_func($callback, $a[$key], $b[$key]);
        });
    }
    

    It works well on string values by default, but you'll have to sub the callback for a number comparison function if all your values are numbers.

提交回复
热议问题