php- 查找重复项并按数组排序 属性

php- find duplicate and sort by array property

我有大量关联产品。我想检查是否有重复 产品,然后获得低价 的产品。

我可以使用array_uniquearray_count_values来查找重复记录,但我不知道如何处理排序部分。

数组属性:

样本数据


Array
(
    [0] => Array
        (
            [product_id] => 1111
            [title] => Product 1
            [price] => 140
        )

    [1] => Array
        (
            [product_id] => 2222
            [title] => Product 2
            [price] => 66
        )

    [2] => Array
        (
            [product_id] => 1111
            [title] => Product 1 A
            [price] => 123
        )

    [3] => Array
        (
            [product_id] => 3333
            [title] => Product 3
            [price] => 37.4
        )

    [4] => Array
        (
            [product_id] => 4444
            [title] => Product 4
            [price] => 10.5
        )

)



产品 1 重复,因此将有一条针对产品 1 的记录,应保留低价。

输出应该像


Array
(
    [0] => Array
        (
            [product_id] => 1111
            [title] => Product 1
            [price] => 123
        )

    [1] => Array
        (
            [product_id] => 2222
            [title] => Product 2
            [price] => 66
        )  

    [2] => Array
        (
            [product_id] => 3333
            [title] => Product 3
            [price] => 37.4
        )

    [3] => Array
        (
            [product_id] => 4444
            [title] => Product 4
            [price] => 10.5
        )

)

这将创建一个仅包含唯一 product_id 的数组,仅显示每个 product_id 的最低价格:

$products_lowestprices = [];

foreach ( $products AS &$product ) {

  if ( isset( $products_lowestprices[ $product[ 'product_id' ] ] ) ) {
    if ( $products_lowestprices[ $product[ 'product_id' ] ][ 'price' ] > $product[ 'price' ] ) {
      $products_lowestprices[ $product[ 'product_id' ] ] = $product;
    }
  } else {
    $products_lowestprices[ $product[ 'product_id' ] ] = $product;
  }

}

$products_lowestprices = array_values( $products_lowestprices );