We often face such a demand. Although sometimes we can sort the data directly when querying the database, it still cannot meet the increasingly complex business needs. Two functions will be used here. One is the array_column() function, which accepts three parameters. For details, see here. Extract the value of a key from a two-dimensional array and return it as a new array.
The other is the array_multisort() function. This function is a sorting function. For details, see here.
It will follow the sorting rules of the first parameter array and the value of the first parameter array. Sorts the third argument in the position where it is heavy.
Can’t you understand? It’s okay if you don’t understand it, it’s better to look at the code directly:
$orgin = array( array( 'id' => 5698, 'first_name' => 'Bill', 'last_name' => 'Gates', ), array( 'id' => 4767, 'first_name' => 'Steve', 'last_name' => 'Jobs', ), array( 'id' => 3809, 'first_name' => 'Mark', 'last_name' => 'Zuckerberg', ) ); $idArr = array_column($orgin, 'id'); array_multisort($idArr,SORT_ASC,$orgin); var_dump($orgin);
The printed result is:
array (size=3) 0 => array (size=3) 'id' => int 3809 'first_name' => string 'Mark' (length=4) 'last_name' => string 'Zuckerberg' (length=10) 1 => array (size=3) 'id' => int 4767 'first_name' => string 'Steve' (length=5) 'last_name' => string 'Jobs' (length=4) 2 => array (size=3) 'id' => int 5698 'first_name' => string 'Bill' (length=4) 'last_name' => string 'Gates' (length=5)
Related recommendations:
PHP custom two-dimensional array sorting function array
Several PHP ways to sort two-dimensional arrays
PHP multi-dimensional array sorting algorithm analysis
The above is the detailed content of PHP function to sort two-dimensional array. For more information, please follow other related articles on the PHP Chinese website!