views:

43

answers:

1

so I have two arrays. one of them looks like this (it's values or the number of elements can change):

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 one shouldn't change, elements and values are the same every time).

notice the first one has a few elements from the 2nd one. How can I sort the 2nd array based on the elements from the 1st one?

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 one are moved at the top, in the same order as the 1st, and the others are left alone).

A: 

Stability was a twist, as PHP doesn't respect that any longer, but a little extra work keeps the sort 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'));

// utility to swap values for keys.
function invert($array) {
    $result = array();
    while(list($key, $value) = each($array))
        $result[$value] = $key;
    return $result;
}

// create a lookup table for sorted order to avoid repeated searches
$order_index = invert($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 = invert($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);
Chadwick