Search code examples
phparrayssortingksortcustom-sort

Sort a flat associative array by its keys according to the key order of another associative array


I have two arrays.

One is a larger bit of data:

Array
(
    [12] => blah
    [36] => foo
    [58] => blah
    [60] => blah
    [72] => blah
    [90] => bar
)

The other is a smaller subset of different but related data in a different order, with each key corresponding to the same key in the larger array:

Array
(
    [36] => foo data
    [90] => bar data
    [12] => blah data
)

Now, my question is, how do I get the first array to be in such an order so that the keys in the first array that have corresponding keys in the second array will appear first and in the same order as the second array?

Thus, like this:

Array
(
    [36] => foo
    [90] => bar
    [12] => blah
    [58] => blah
    [60] => blah
    [72] => blah
)

Solution

  • $array1 = array(12 => 1, 36 => 2, 58 => 3, 60 => 4, 72 => 5);
    $array2 = array(36 => 1, 60 => 2, 12 => 1);
    
    # obtaining keys in the order of question    
    $result = array_intersect_key($array2, $array1);
    
    # assign values from original $array1
    foreach($result as $key => &$value) {
        $value = $array1[$key];
    }
    unset($value); # kill reference for safety
    
    # add missing elements from $array1
    $result += $array1;
    
    var_dump($result);
    

    Output:

    array(5) {
      [36]=>
      int(2)
      [60]=>
      int(4)
      [12]=>
      int(1)
      [58]=>
      int(3)
      [72]=>
      int(5)
    }
    

    See Array Operators for the + for arrays.