在另一个数组中按 属性 对数组进行排序

Sort array by property in another array

我有两个相同大小的数组。一个包含所有产品信息,另一个仅包含 product_id 和位置。我想按照第二个数组中指定的顺序对第一个数组进行排序。现在我有这段代码,但必须有更有效的方法来做到这一点。

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

这将删除双 for 循环:

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