Home >Backend Development >PHP Tutorial >A simple method to implement multi-dimensional array sorting in PHP
The example in this article describes how to simply implement multi-dimensional array sorting in PHP. Share it with everyone for your reference, the details are as follows:
When I was doing a function before, I had to put the data into a two-dimensional array and sort it, and then go online to find solutions.
The array_multisort function will be used at this time. The array_multisort() function sorts multiple arrays or multi-dimensional arrays
Let’s look at an example first
<?php $data=array( 0=>array('one'=>34,'two'=>'d'), 1=>array('one'=>45,'two'=>'e'), 2=>array('one'=>47,'two'=>'h'), 3=>array('one'=>12,'two'=>'c'), 4=>array('one'=>15,'two'=>'w'), 5=>array('one'=>85,'two'=>'r'), ); foreach($data as $val){ $key_arrays[]=$val['one']; } array_multisort($key_arrays,SORT_ASC,SORT_NUMERIC,$data); var_dump($data);
The output result: Sort by key value one, as follows:
array 0 => array 'one' => int 12 'two' => string 'c' (length=1) 1 => array 'one' => int 15 'two' => string 'w' (length=1) 2 => array 'one' => int 34 'two' => string 'd' (length=1) 3 => array 'one' => int 45 'two' => string 'e' (length=1) 4 => array 'one' => int 47 'two' => string 'h' (length=1) 5 => array 'one' => int 85 'two' => string 'r' (length=1)
php Multi-dimensional array sort
The following is encapsulated into a function for easy use
function my_array_multisort($data,$sort_order_field,$sort_order=SORT_ASC,$sort_type=SORT_NUMERIC){ foreach($data as $val){ $key_arrays[]=$val[$sort_order_field]; } array_multisort($key_arrays,SORT_ASC,SORT_NUMERIC,$data); rturn $data; }
I hope this article will be helpful to everyone in PHP programming.
For more articles on how to simply implement multi-dimensional array sorting in PHP, please pay attention to the PHP Chinese website!