2

I have an multidimensional array:

    Array
(
    [0] => Array
        (
            [Id] => 1
            [MTime_Id] => 1
            [MName] => Breakfast
            [DName] => Other Cereals
            [IName] => 
            [Date] => 2013-02-05
        )

[1] => Array
    (
        [Id] => 1
        [MTime_Id] => 1
        [MName] => Breakfast
        [DName] => Porridge
        [IName] => Oats,Milk,Sugar
        [Date] => 2013-02-06
    )

[2] => Array
    (
        [Id] => 1
        [MTime_Id] => 1
        [MName] => Breakfast
        [DName] => Porridge
        [IName] => Oats,Milk,Sugar,Oats,Milk,Sugar
        [Date] => 2013-02-05
    )

)

And I am trying to use array unique to filter this

 [IName] => Oats,Milk,Sugar,Oats,Milk,Sugar

I am having no luck. How can I filter the duplicates?

Cheers.

bobo2000
  • 1,779
  • 7
  • 31
  • 54

3 Answers3

1

If you filter input and therefore don't have extra spaces in IName field, you can use something as simple as this for filtering:

$array[2]['IName'] = implode(',', array_unique(explode(',', $array[2]['IName'])));
Ranty
  • 3,333
  • 3
  • 22
  • 24
0

The problem is that you habe in array two Oats,Milk,Sugar as element of IName, in array three you have Oats,Milk,Sugar,Oats,Milk,Sugar. This is not the same!

"Oats,Milk,Sugar"=="Oats,Milk,Sugar,Oats,Milk,Sugar" (or "Oats,Milk,Sugar".equals("Oats,Milk,Sugar,Oats,Milk,Sugar")) is false.

If you want to have it unique you have to explode the single results and then do a unique on it or you have to store the single values in seperate fields...

BTW: Here is a link how to remove duplicates from a multi dimensional array How to remove duplicate values from a multi-dimensional array in PHP

Community
  • 1
  • 1
TerenceJackson
  • 1,776
  • 15
  • 24
  • http://stackoverflow.com/questions/2613063/remove-duplicate-from-string-in-php I think this is what I am trying to do, but the code does not work. – bobo2000 Feb 07 '13 at 15:22
0

I am not sure if a function exists for that, here is a simple solution, you can loop the array, and get the result of each value, then explode result, and insert it into an array. then use the array_unique function. try this:

$result = array();
foreach($arrays as $array)
{
    $tmp = $array['IName'];
    $tmp2 = explode(',',$tmp);
    foreach ($tmp2 as $t)
    {
        $result[]=$t;
    }
}
$array_unique = array_unique($result);