Search code examples
phpsortinglarge-dataarray-unique

php- find duplicate and sort by array property


I have a large associative array of products. i want to check if there are duplicate products then get product with low price.

I can use array_unique and array_count_values to find duplicate records, but I don't know how to handle sorting part.

array properties:

  • product_id (unique)
  • title
  • price

sample data


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
        )

)



product 1 is duplicated so there will be one record against product 1 and with low price should be kept.

output should be like


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
        )

)


Solution

  • This will create an array that has only unique product_id's showing only the lowest price for each 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 );