Combine two sorted arrays, and the resulting array must also be sorted

Let's say you have two arrays of arrays with the same structure, but they have several array counters:

$arr1 = array(array(1,"b"), array(2,"a"), array(5,"c")); $arr2 = array(array(3,"e")); 

Now the data in $ arr1 and $ arr2 are sorted, and now I would like to combine these two arrays, so I did this:

 $res = array_merge($arr1, $arr2); 

And then I get the output as follows:

 1-b 2-a 5-c 3-e 

But I would like the sorted $ res to also look like this:

 1-b 2-a 3-e 5-c 

I wonder if there is a function in PHP for this automatically, without having to write your own function? Or please tell me why this is the best approach for this, if I want (later) to add sorting by the following parameter, so that the result is like this:

 2-a 1-b 5-c 3-e 

Thank you for your help.

+4
source share
3 answers

You can combine arrays first, and then sort the final array.

You are probably looking for a multisort function. I usually use this function (I found this function somewhere on the Internet a few years ago, loans go to the original author):

 /* * sort a multi demensional array on a column * * @param array $array array with hash array * @param mixed $column key that you want to sort on * @param enum $order asc or desc */ function array_qsort2 (&$array, $column=0, $order="ASC") { $oper = ($order == "ASC")?">":"<"; if(!is_array($array)) return; usort($array, create_function('$a,$b',"return (\$a['$column'] $oper \$b['$column']);")); reset($array); } 

You can use it as follows:

 array_qsort2($res, 0, "ASC"); 
+3
source

Why not just call ksort($res) after your array_merge?

+1
source

Since php v5.3 you can use anon functions in a more natural way,

 <?php $arr1 = array(array(1,"b"), array(2,"a"), array(5,"c")); $arr2 = array(array(3,"e")); $res = array_merge($arr1, $arr2); usort($res, function($a,$b) { // php7 // return $a[0] <=> $b[0]; if ($a[0] == $b[0]) return 0; return $a[0] < $b[0] ? -1 : 1; }); print_r($res); 

Output

 Array ( [0] => Array ( [0] => 1 [1] => b ) [1] => Array ( [0] => 2 [1] => a ) [2] => Array ( [0] => 3 [1] => e ) [3] => Array ( [0] => 5 [1] => c ) ) 
+1
source

Source: https://habr.com/ru/post/1340594/


All Articles