0

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.

3
  • What ahve you tried and where were you stuck? There are plenty of examples for similar problems both on and off the site, they should've gotten you at least halfway to a solution. Commented Jun 4, 2021 at 9:04
  • please show us your best attempt at solving your issue, you might be closer than you think! Suggested reading How to Ask. Commented Jun 4, 2021 at 9:11
  • You use ['id'], but the array you're trying to sort is not associative. You have marked the 0 index as the one with the order id, so you should try [0] instead. P.S. This should be giving you Undefined index notices. Commented Jun 4, 2021 at 9:19

2 Answers 2

1

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

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

Comments

0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.