Search code examples
phpperformancesortingquicksortusort

Sort array by property in another array


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

Solution

  • 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];
    });