hans
hans

Reputation: 29

Sort a 2d array by values in a column related to a flat priority array

I have an array with IDs that looks like

 $order_ids = array(8,9,10,4,7);

and another multidimensional array that looks like

$multiarray = [
    [4, 23, 1],
    [9, 66, 4],
    [8, 17, 3],
];

I tried

 $keys = array_flip($order_ids);

 usort($multiarray, function($a, $b) use ($keys)
 {
     return $keys[$a] - $keys[$b[0];
 });

The order_ids of the 2nd array correspond to the values in the first array. What I need to do is sort the 2nd array by the order_ids in the order they are in the 1st array.

Upvotes: 0

Views: 37

Answers (2)

mickmackusa
mickmackusa

Reputation: 47864

Reference the flipped lookup array to compare values by their priority value. Demo

$map = array_flip($order_ids);

usort($array, fn($a, $b) => $map[$a[0]] <=> $map[$b[0]]);

var_export($array);

Upvotes: 0

jibsteroos
jibsteroos

Reputation: 1391

You could cycle through the records in $arr and store them in the order set by $order_ids - result in $newArr:

<?php
$order_ids = array(8,9,10,4,7);

$arr = [
    [4, 23, 1],
    [9, 66, 4],
    [8, 17, 3],
];

foreach($order_ids as $id) {
    foreach($arr as $record) {
        if($record[0] == $id) {
            $newArr[] = $record;
            break;
        }
    }
}

demo

Upvotes: 1

Related Questions