简体   繁体   中英

Merge Sort Together Two Arrays in Php?

I'm new to PHP , so maybe I'm missing something simple. I have two multidimensional hashes of the form:

Array1:
'x' => Array ( 'a' => num1, 'b' => '1' ), 
'y' => Array ( 'a' => num3, 'b' => '3' ), 
'z' => Array ( 'a' => num5, 'b' => '5' ) 

Array2:
'w' => Array ( 'a' => num1, 'b' => '2' ), 
'q' => Array ( 'a' => num3, 'b' => '4' ), 
'r' => Array ( 'a' => num5, 'b' => '6' ) 

Both arrays are sorted by b. All I want to do is merge them together to get a list of the keys sorted by b. This should be a trivial O(n) operation a la merge sort, but I can't find any elegant way of doing this in php with its 50 different sort functions. The result should be:

array('x','w','y','q','z','r')

I'm fine with using a typical sort at O(nlogn) for this if it's a much shorter solution. I really want to avoid a ton of messy code for the merge/sort function.

You can just union the arrays and then sort the result by b :

$union = $arr1 + $arr2;
uasort($union, function($a, $b){
    return $a['b'] - $b['b'];
});
$result = array_keys($union);

Live Demo

If you still want a O(n) solution this should do it and it's not overly complex, however note that it may be slower unless you are dealing with very large arrays:

$result = array(); 
$keys = array_keys($arr2);
$i = 0;
foreach($arr1 as $key => $value){
    while($arr2[$keys[$i]]['b'] < $value['b'])
        $result[] = $keys[$i++];
    $result[] = $key;
}
$result = array_merge($result, array_slice($keys, $i));

Live Demo

I have no idea which one of these solutions will achieve the desired result faster in your case. The first one seems more readable though.

EDIT

Just noticed you wanted a different result. I misunderstood and thought you wanted to merge the arrays but keep that b key in order. Oops! I'll leave this for reference.


A nice and easy way:

$array1 = array(
    'x' => array ( 'a' => 1, 'b' => '1' ),
    'y' => array ( 'a' => 3, 'b' => '3' ),
    'z' => array ( 'a' => 5, 'b' => '5' )
);

$array2 = array(
    'w' => array ( 'a' => 1, 'b' => '2' ),
    'q' => array ( 'a' => 3, 'b' => '4' ),
    'r' => array ( 'a' => 5, 'b' => '6' ) 
);

$merged = array_merge_recursive($array1, $array2);

Yields:

array(6) {
  ["x"]=>
  array(2) {
    ["a"]=>
    int(1)
    ["b"]=>
    string(1) "1"
  }
  ["w"]=>
  array(2) {
    ["a"]=>
    int(1)
    ["b"]=>
    string(1) "2"
  }
  ["y"]=>
  array(2) {
    ["a"]=>
    int(3)
    ["b"]=>
    string(1) "3"
  }
  ["q"]=>
  array(2) {
    ["a"]=>
    int(3)
    ["b"]=>
    string(1) "4"
  }
  ["z"]=>
  array(2) {
    ["a"]=>
    int(5)
    ["b"]=>
    string(1) "5"
  }
  ["r"]=>
  array(2) {
    ["a"]=>
    int(5)
    ["b"]=>
    string(1) "6"
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM