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

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

    Here is a method that I found long ago and cleaned up a bit. This works great, and can be quickly changed to accept objects as well.

    /**
     * A method for sorting arrays by a certain key:value.
     * SortByKey is the key you wish to sort by
     * Direction can be ASC or DESC.
     *
     * @param $array
     * @param $sortByKey
     * @param $sortDirection
     * @return array
     */
    private function sortArray($array, $sortByKey, $sortDirection) {
    
        $sortArray = array();
        $tempArray = array();
    
        foreach ( $array as $key => $value ) {
            $tempArray[] = strtolower( $value[ $sortByKey ] );
        }
    
        if($sortDirection=='ASC'){ asort($tempArray ); }
            else{ arsort($tempArray ); }
    
        foreach ( $tempArray as $key => $temp ){
            $sortArray[] = $array[ $key ];
        }
    
        return $sortArray;
    
    }
    

    to change the method to sort objects simply change the following line:

    $tempArray[] = strtolower( $value[ $sortByKey ] ); to $tempArray[] = strtolower( $value->$sortByKey );

    To run the method simply do

    sortArray($inventory,'price','ASC');

提交回复
热议问题