PHP - sorting array elements based on other array elements :)

so i have two arrays. one of them looks like this (values ​​or the number of elements may vary):

array('4dec' , 'def3', 'a3d6', 'd12f');

and the other:

array(array('id' => 'd12f', 'name' => 'John'),
      array('id' => 'a5f1', 'name' => 'Kathy'),
      array('id' => 'def3', 'name' => 'Jane'),
      array('id' => 'a3d6', 'name' => 'Amy'),
      array('id' => '4dec', 'name' => 'Mary'),      
      array('id' => 'ecc2', 'name' => 'Fred'));

(this should not change, elements and values ​​are the same every time).

notice that the first has several elements from the second. How can I sort the second array based on the elements from the first?

so basically, in this case the 2nd array should become:

array(array('id' => '4dec', 'name' => 'Mary'),
      array('id' => 'def3', 'name' => 'Jane'),
      array('id' => 'a3d6', 'name' => 'Amy'),
      array('id' => 'd12f', 'name' => 'John'),
      array('id' => 'a5f1', 'name' => 'Kathy'),
      array('id' => 'ecc2', 'name' => 'Fred'));

(the elements that exist in the 1st move above, in the same order as the 1st, and the rest are left alone).

+4
source share
1 answer

Stability was a highlight since PHP no longer respects this, but a little extra work keeps the sorting stable.

$order_by = array('4dec' , 'def3', 'a3d6', 'd12f');

$data = array(array('id' => 'd12f', 'name' => 'John'),
              array('id' => 'a5f1', 'name' => 'Kathy'),
              array('id' => 'def3', 'name' => 'Jane'),
              array('id' => 'a3d6', 'name' => 'Amy'),
              array('id' => '4dec', 'name' => 'Mary'),      
              array('id' => 'ecc2', 'name' => 'Fred'));

// create a lookup table for sorted order to avoid repeated searches
$order_index = array_flip($order_by);

// create a lookup table for original order: in PHP 4.1.0 usort became unstable
// http://www.php.net/manual/en/function.usort.php
$orig_order_by = array_map(function($a){return $a['id'];}, $data);
$orig_index = array_flip($orig_order_by);

// sort values by specified order, with stability
$compare = function($a, $b) use (&$order_index, &$orig_index) {
    $aid = $a['id'];
    $bid = $b['id'];

    $ai = $order_index[$aid];
    $bi = $order_index[$bid];

    if ($ai === null and $bi === null) { // original sort order for stability
        return $orig_index[$aid] - $orig_index[$bid];
    }
    if ($ai === null) { return 1; }
    if ($bi === null) { return -1; }

    return $ai - $bi;
};
usort($data, $compare);
var_dump($data);
+4

All Articles