Tuesday, 28 August 2018

Merge 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 different count of arrays in them:


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

Now, the data in the $arr1 and $arr2 is sorted, and now what I would like it to merge these two arrays, so I did this:
$res = array_merge($arr1, $arr2);

And then I get an output like this:
1-b
2-a
5-c
3-e

But, I would like to have a sorted $res also like this:
1-b
2-a
3-e
5-c

I wonder if there's a function in PHP to do this automatically, without me having to write my own function? Or, please advise me on which is the best approach for this if I want to (later on) add sorting by the next parameter so the output would be like this
2-a
1-b
5-c
3-e

Thank you for all your help.

You can first merge the arrays and then sort the final array.
You are probably looking for a multi-sort function. I usually use this function (I found this functions somewhere on the internet years ago, credits 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 like this:
array_qsort2($res, 0, "ASC");

0 comments:

Post a Comment