0

I have two arrays of the same size. One contains all product information and the other one contains only product_id and position. I want to order the first array by the order specified in the second array. Right now I have this code but there must be a more efficient way to do it.

        foreach ($ret_products as $ret_product) {
            foreach ($sort as $sort_product) {
                if ($ret_product->id === $sort_product['product_id']) {
                    $ret_product->sort_position = $sort_product['position'];
                }
            }
        }
         usort($ret_products, function($a, $b){ 
            return $a->sort_position > $b->sort_position;
        });
2

This removes the double for loop:

$order = [];
foreach ($sort as $sort_product) {
  $order[$sort_product['product_id']] = $sort_product['position'];
}

usort($ret_products, function($a, $b) use ($order) {
  return $order[$a->id] > $order[b->id];
});
  • 1
    You can also use array_column($sort, 'position', 'product_id') to make $order. – Don't Panic Oct 18 '18 at 22:00
  • This isn't working, getting a php error saying order is undefined in the usort return – compsci45000 Oct 19 '18 at 0:37
  • 1
    Heres the solution: usort($ret_products, function($a, $b) use($order){ return $order[$a->id] > $order[$b->id]; }); – compsci45000 Oct 19 '18 at 0:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.