代码之家  ›  专栏  ›  技术社区  ›  user3554045

php-查找重复项并按数组属性排序[关闭]

  •  0
  • user3554045  · 技术社区  · 7 年前

    我有一个庞大的产品关联阵列。我想看看有没有 复制 产品然后获得产品 .

    我可以使用 array\u唯一 array\u count\u值 查找重复记录,但我不知道如何处理排序部分。

    阵列属性:

    • 产品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
            )
    
    )
    
    
    1 回复  |  直到 7 年前
        1
  •  0
  •   Ben Shoval    7 年前

    这将创建一个只有唯一product\u id的数组,该数组仅显示每个product\u 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 );