How to sort multi-dimensional array (PHP)?

后端 未结 2 365
野趣味
野趣味 2021-01-16 11:25

How to sort this array by pos attribute even though keys (name, store_id, product etc.)

[Attributes] => Array
(         


        
2条回答
  •  深忆病人
    2021-01-16 12:27

    Have a look at the PHP function array_multisort.

    http://php.net/manual/en/function.array-multisort.php

    There is an example-function in the comments, which should be fine for you:

    function array_orderby()
    {
        $args = func_get_args();
        $data = array_shift($args);
        foreach ($args as $n => $field) {
            if (is_string($field)) {
                $tmp = array();
                foreach ($data as $key => $row)
                    $tmp[$key] = $row[$field];
                $args[$n] = $tmp;
                }
        }
        $args[] = &$data;
        call_user_func_array('array_multisort', $args);
        return array_pop($args);
    }
    
    // $dataArray is the array that contains your data
    $sorted = array_orderby($dataArray, 'pos', SORT_DESC);
    

提交回复
热议问题