8

I have this issue with multidimensional arrays.

Given the following multidimensional array:

Array(
[0] => Array("a", "b", "c")
[1] => Array("x", "y", "z")
[2] => Array("a", "b", "c")
[3] => Array("a", "b", "c")
[4] => Array("a", "x", "z")
)

I want to check its values and find duplicates (i.e. keys 0, 2 and 3) leaving just one key - value pair deleting the others, resulting in somthing like this:

Array(
    [0] => Array("a", "b", "c")
    [1] => Array("x", "y", "z")
    [2] => Array("a", "x", "z")
    )

How can I do that??

1

6 Answers 6

17

This will remove duplicate items from your array using array_unique():

$new_arr = array_unique($arr, SORT_REGULAR);
Sign up to request clarification or add additional context in comments.

8 Comments

-1 Look at the docs. This will convert the values of the array to strings before comparing.
@Artefacto: Look at the docs. I'm using the SORT_REGULAR flag which does NOT use string comparison.
as per php document "Note that array_unique() is not intended to work on multi dimensional arrays.". It can be seen from the given link.
@enam I think it just means that array_unique doesn't flatten the array to find the uniques. (btw, +1)
Thought array_unique doesn't work with multidimensional arrays.
|
8

You can simply do it using in_array()

$data = Array(
    0 => Array("a", "b", "c"),
    1 => Array("x", "y", "z"),
    2 => Array("a", "b", "c"),
    3 => Array("a", "b", "c"),
    4 => Array("a", "x", "z"),
);

$final = array();
foreach ($data as $array) {
    if(!in_array($array, $final)){
        $final[] = $array;
    }
}

which will get you something like

array(3) {
  [0] => array(3) {
    [0] => string(1) "a"
    [1] => string(1) "b"
    [2] => string(1) "c"
  }
  [1] => array(3) {
    [0] => string(1) "x"
    [1] => string(1) "y"
    [2] => string(1) "z"
  }
  [2] => array(3) {
    [0] => string(1) "a"
    [1] => string(1) "x"
    [2] => string(1) "z"
  }
}

Comments

1

You can go smart with serialization for comparison of arrays.

var_dump(makeUnique($data));

function makeUnique(array $data)
{
    $serialized = array_map(create_function('$a', 'return serialize($a);'), $data);
    $unique = array_unique($serialized);
    return array_intersect_key($unique, $data);
}

Have fun

Comments

0
$arr = ...;
$final = array();
sort($arr);
foreach ($arr as $el) {
   if (!isset($prev) || $el !== $prev)
       $final[] = $el
    $prev = $el;
}

This is a more efficient1 solution (log n + n instead of quadratic) but it relies on a total order between all the elements of the array, which you may not have (e.g. if the inner arrays have objects).

1 More efficient than using in_array. Turns out array_unique actually uses this algorithm, so it has the same shortcomings.

Comments

0

To check using array_unique on multidimensional arrays, you need to flatten it out like so, using implode.

    $c=count($array)
    for($i=0;$i<$c;$i++)
    {
    $flattened=implode("~",$array[$i]);
    $newarray[$i]=$flattened;
     }
    if(count(array_unique($newarray)
    <count($newarray))
    {
    //returns true if $array contains duplicates
    //can also use array_unique on $newarray 
    //to remove   duplicates, then explode, 
    //to return to default state
    }

Hope this is helpful, took sometime to get it.

1 Comment

Could you fix encoding mistake ?
0
**This is example array**
$multi_com=[
    [
        {
            "combination_id": "19"
        },
        {
            "combination_id": "20"
        },
        {
            "combination_id": "21"
        }
    ],
    [
        {
            "combination_id": "18"
        },
        {
            "combination_id": "20"
        },
        {
            "combination_id": "22"
        }
    ],
    [
        {
            "combination_id": "20"
        },
        {
            "combination_id": "21"
        }
    ]
]

**This is sample code**
        $array1 = [];
        $array2 = [];
        $status = false;
        foreach ($multi_com as $key => $val) {
            foreach ($val as $key2 => $val2) {
                if (count($array1) !== 0) {
                    $array_res = in_array($val2->combination_id, $array1);
                    if ($array_res) {
                        $array2[] = $val2->combination_id;
                    }
                }
            }

            if (!$status) {
                for ($x = 0; $x < count($val); $x++) {
                    $array1[] = $val[$x]->combination_id;
                }
            } else {
                $array1 = [];
                $array1 = $array2;
                $array2 = [];
            }
            $status = true;
        }

        return $array1;

1 Comment

return $array1=[20]

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.