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

前端 未结 19 1850
清酒与你
清酒与你 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');
    
    0 讨论(0)
  • 2020-11-22 00:20

    From Sort an array of associative arrays by value of given key in php:

    by using usort (http://php.net/usort) , we can sort an array in ascending and descending order. just we need to create a function and pass it as parameter in usort. As per below example used greater than for ascending order if we passed less than condition then it's sort in descending order. Example :

    $array = array(
      array('price'=>'1000.50','product'=>'test1'),
      array('price'=>'8800.50','product'=>'test2'),
      array('price'=>'200.0','product'=>'test3')
    );
    
    function cmp($a, $b) {
      return $a['price'] > $b['price'];
    }
    
    usort($array, "cmp");
    print_r($array);
    

    Output:

    Array
     (
        [0] => Array
            (
                [price] => 200.0
                [product] => test3
            )
    
        [1] => Array
            (
                [price] => 1000.50
                [product] => test1
            )
    
        [2] => Array
            (
                [price] => 8800.50
                [product] => test2
            )
      )
    
    0 讨论(0)
  • 2020-11-22 00:21

    try this:

    $prices = array_column($inventory, 'price');
    array_multisort($prices, SORT_DESC, $inventory);
    print_r($inventory);
    
    0 讨论(0)
  • 2020-11-22 00:24

    You might try to define your own comparison function and then use usort.

    0 讨论(0)
  • 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');

    0 讨论(0)
  • 2020-11-22 00:30
    //Just in one line custom function
    function cmp($a, $b)
    {
    return (float) $a['price'] < (float)$b['price'];
    }
    @uasort($inventory, "cmp");
    print_r($inventory);
    
    //result
    
    Array
    (
    [2] => Array
        (
            [type] => pork
            [price] => 5.43
        )
    
    [0] => Array
        (
            [type] => fruit
            [price] => 3.5
        )
    
    [1] => Array
        (
            [type] => milk
            [price] => 2.9
        )
    
    )
    
    0 讨论(0)
提交回复
热议问题