0

I have two arrays that need to reflect the same order based on one particular value. My first array, $array1, is a series of integers, and I need the secondary arrays in $array2, which have these same integers as a value (along with a whole bunch of other data that I have left off here for brevity), to be re-sorted to reflect the order of the integers in $array1.

Currently I have:

$array1 = array(
   [0] => 19,
   [1] => 15,
   [2] => 18,
   [3] => 20
);

$array2 = array (
   [0] => array (
       [0] => 20,
       [1] => 'Some other data.'
   ),
   [1] => array (
       [0] => 18,
       [1] => 'Some other data.'
   ),
   [2] => array (
       [0] => 19,
       [1] => 'Some other data.'
   ),
   [3] => array (
       [0] => 15,
       [1] => 'Some other data.'
   )
);

Desired sorting of $array2:

$array2 = array (
   [0] => array (
       [0] => 19,
       [1] => 'Some other data.'
   ),
   [1] => array (
       [0] => 15,
       [1] => 'Some other data.'
   ),
   [2] => array (
       [0] => 18,
       [1] => 'Some other data.'
   ),
   [3] => array (
       [0] => 20,
       [1] => 'Some other data.'
   )
)
0

2 Answers 2

0

In this case you should use uasort()

function cmp($a, $b) {
    $posA = array_search($a[0], $array1);
    $posB = array_search($b[0], $array1);

    if ($posA == $posB) {
        return 0;
    }
    return ($posA < $posB) ? -1 : 1;
}

uasort($array2, 'cmp');

But it will be slow...

Sign up to request clarification or add additional context in comments.

Comments

0
// make order in form "what => place"
$flip = array_flip($array1);

$new = array();
foreach($array2 as $key=>$item) {
   $i = $item[0];
   $new[$flip[$i]] = $item;
}

demo on eval.in

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.