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

前端 未结 19 1816
清酒与你
清酒与你 2020-11-21 23:34

Given this array:

$inventory = array(

   array(\"type\"=>\"fruit\", \"price\"=>3.50),
   array(\"type\"=>\"milk\", \"price\"=>2.90),
   array(\"         


        
19条回答
  •  -上瘾入骨i
    2020-11-22 00:35

    For PHP 7 and later versions.

    /**
     * A method for sorting associative arrays by a key and a direction.
     * Direction can be ASC or DESC.
     *
     * @param $array
     * @param $key
     * @param $direction
     * @return mixed $array
     */
    function sortAssociativeArrayByKey($array, $key, $direction){
    
        switch ($direction){
            case "ASC":
                usort($array, function ($first, $second) use ($key) {
                    return $first[$key] <=> $second[$key];
                });
                break;
            case "DESC":
                usort($array, function ($first, $second) use ($key) {
                    return $second[$key] <=> $first[$key];
                });
                break;
            default:
                break;
        }
    
        return $array;
    }
    

    Usage:

    $inventory = sortAssociativeArrayByKey($inventory, "price", "ASC");
    

提交回复
热议问题