Search code examples
phparraysmagento

How to find duplicate value in sample array


How to find duplicate value in sample array using php

Array
(
    [id] => 644
    [qty] => 1
    [product] => 127
    [super_attribute] => Array
        (
            [140] => 16
        )

)
Array
(
    [id] => 648
    [qty] => 1
    [product] => 111
    [super_attribute] => Array
        (
            [140] => 18
        )

)
Array
(
    [id] => 652
    [qty] => 1
    [product] => 111
    [super_attribute] => Array
        (
            [140] => 18
        )

)

in this above array i want to find duplicate [product] => 111 and [140] => 18 . How can i achieve this?


Solution

  • One possible way to do this is to combine the two elements you're looking for into one longer key, then create a two-dimensional array listing all the IDs that have the new key.

    In the code below I have multiplied the product number by 1000, added the value of super_attribute[140] and cast the result to a string. There are other ways you might obtain a new key depending on what you know about the data you're working with.

    <?php
    $arr  = [
        [
    
        "id" => 644,
        "qty" => 1,
        "product" => 127,
        "super_attribute" => [
            "140" => 16
            ]
        ],
    
        [
        "id" => 648,
        "qty" => 1,
        "product" => 111,
        "super_attribute" => [
            "140" => 18
            ]
        ],
        [
            "id" => 652,
            "qty" => 1,
            "product" => 111,
            "super_attribute" => [
                "140" => 18
            ]
        ]
    ];
    
    $dup = [];
    
    foreach($arr as $subArr) {
        // Calculate the new combined key
        $newKey = (string)($subArr['product']*10000+$subArr["super_attribute"][140]);
    
        // If we don't have this new key, create an array with the ID,
        // otherwise, add the ID to the existing array for the new key.
        if (isset($dup[$newKey])) {
            $dup[$newKey][] = $subArr['id'];
        } else {
            $dup[$newKey] = [$subArr['id']];
        }
    }
    
    var_dump($dup);
    

    Output:

    array (size=2)
      1270016 => 
        array (size=1)
          0 => int 644
      1110018 => 
        array (size=2)    //IDs with the combined key 111 and 18
          0 => int 648    
          1 => int 652