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

问题描述:

我有一个大的产品关联数组。我想检查是否有重复产品,然后获得产品与低价格php-查找重复和按数组属性排序

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

阵列属性:

  • PRODUCT_ID(唯一)
  • 标题
  • 价格

样本数据

 

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 
     ) 

) 

+2

显示阵列的样品。 – AbraCadaver

+0

^你试过了什么 –

+0

什么是重复?你说'product_id'是唯一的。 – HtmHell

这将创建一个数组只有唯一的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); 
+0

@ user3554045很高兴我能帮助! –