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

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

    Complete Dynamic Function I jumped here for associative array sorting and found this amazing function on http://php.net/manual/en/function.sort.php. This function is very dynamic that sort in ascending and descending order with specified key.

    Simple function to sort an array by a specific key. Maintains index association

     0) {
            foreach ($array as $k => $v) {
                if (is_array($v)) {
                    foreach ($v as $k2 => $v2) {
                        if ($k2 == $on) {
                            $sortable_array[$k] = $v2;
                        }
                    }
                } else {
                    $sortable_array[$k] = $v;
                }
            }
    
            switch ($order) {
                case SORT_ASC:
                    asort($sortable_array);
                break;
                case SORT_DESC:
                    arsort($sortable_array);
                break;
            }
    
            foreach ($sortable_array as $k => $v) {
                $new_array[$k] = $array[$k];
            }
        }
    
        return $new_array;
    }
    
    $people = array(
        12345 => array(
            'id' => 12345,
            'first_name' => 'Joe',
            'surname' => 'Bloggs',
            'age' => 23,
            'sex' => 'm'
        ),
        12346 => array(
            'id' => 12346,
            'first_name' => 'Adam',
            'surname' => 'Smith',
            'age' => 18,
            'sex' => 'm'
        ),
        12347 => array(
            'id' => 12347,
            'first_name' => 'Amy',
            'surname' => 'Jones',
            'age' => 21,
            'sex' => 'f'
        )
    );
    
    print_r(array_sort($people, 'age', SORT_DESC)); // Sort by oldest first
    print_r(array_sort($people, 'surname', SORT_ASC)); // Sort by surname
    

提交回复
热议问题