1

I have a simple problem. Lets say I have an array

Array

0   
product_id  233
slug    "zotac-geforce-gtx-1070-amp-extreme-edition-8gb-zt-p10700b-10p"

1   
product_id  227
slug    "zotac-geforce-gtx-1060-mini-6gb-gddr5-zt-p10600a-10l"

2   
product_id  233
slug    "zotac-geforce-gtx-1070-amp-extreme-edition-8gb-zt-p10700b-10p"

Now if you see there are two products having same product_id! I don't want that I am trying to get this array filtered from duplicate products

This is what I tried but it doesn't work

$temp_products = array();
    foreach($products as $product)
    {
        if(count($temp_products) > 0)
        {
            foreach($temp_products as $temp_product)
            {
                if($temp_product['product_id'] != $product['product_id'])
                {
                    $temp_products[] = $product;
                }
            }
        }
        else
        {
            $temp_products[] = $product;
        }
    }

It returns the same array as the original one. and $products is the main array having the data.

3
  • array_filter removes duplicates if data is the same Commented May 11, 2017 at 12:51
  • You could also check array_unique and its comments. Commented May 11, 2017 at 12:52
  • $products array came from elasticsearch result Commented May 11, 2017 at 13:02

2 Answers 2

1

Try this! But I would definitely suggest using array_filter or array_unique will post an example later. Try this.

$temp_products = array();
    $count = 0;
    foreach($products as $product)
    {

        if(count($temp_products) > 0)
        {
            //foreach($temp_products as $temp_product)
            //{
                if($temp_products[$count]['product_id'] != $product['product_id'])
                {
                    $temp_products[] = $product;
                }
            //}
        }
        else
        {
            $temp_products[] = $product;
        }

    }

Using array_unqiue

    foreach($products as $product)
    {
       $temp_products[] = $product;
    }

    dd(array_unique($temp_products));
Sign up to request clarification or add additional context in comments.

Comments

1

Another way would be to use a helper array to keep track of already present ids.

$temp_products = array();
$already_present = array();
    foreach($products as $product)
    {
      $id = $product['product_id'];
      if ( isset($already_present[ $id ] ) ) continue;
      $temp_products[] = $product;
      $already_present[ $id ] = '';
    }

$products = $temp_products;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.