Home > Article > Backend Development > PHP custom two-dimensional array sorting function array
This time I will bring you php custom two-dimensional array sorting function array, what are the precautions for php custom two-dimensional array sorting function array, the following is a practical case, let's take a look.
This article mainly introduces the usage of php custom two-dimensional array sorting function array_orderby, combined with examples to analyze the related traversal, determination, sorting and other operations of php for sorting two-dimensional arrays Tips, friends in need can refer to
This article describes the usage of PHP's custom two-dimensional array sorting function array_orderby. Share it with everyone for your reference, the details are as follows:
<?php /** I came up with an easy way to sort database-style results. This does what example 3 does, except it takes care of creating those intermediate arrays for you before passing control on to array_multisort(). */ 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); } /* The sorted array is now in the return value of the function instead of being passed by reference. */ $data[] = array('volume' => 67, 'edition' => 2); $data[] = array('volume' => 86, 'edition' => 1); $data[] = array('volume' => 85, 'edition' => 6); $data[] = array('volume' => 98, 'edition' => 2); $data[] = array('volume' => 86, 'edition' => 6); $data[] = array('volume' => 67, 'edition' => 7); // Pass the array, followed by the column names and sort flags $sorted = array_orderby($data, 'volume', SORT_DESC, 'edition', SORT_ASC); print_r($sorted) ?>
Running results:
Array ( [0] => Array ( [volume] => 98 [edition] => 2 ) [1] => Array ( [volume] => 86 [edition] => 1 ) [2] => Array ( [volume] => 86 [edition] => 6 ) [3] => Array ( [volume] => 85 [edition] => 6 ) [4] => Array ( [volume] => 67 [edition] => 2 ) [5] => Array ( [volume] => 67 [edition] => 7 ) )
I believe you have mastered the method after reading the case in this article, For more exciting content, please pay attention to other related articles on the php Chinese website!
Recommended reading:
How the PHP generator uses the access directory service permissions of
ThinkPHP implements WeChat payment (jsapi payment) process tutorial detailed explanation_php example
The above is the detailed content of PHP custom two-dimensional array sorting function array. For more information, please follow other related articles on the PHP Chinese website!