Morgan
Morgan

Reputation: 157

foreach in foreach multiple dimensional

I'd like to know how to avoid dupplicate of element while using a foreach in foreach with multidimensional array ?

The first level of my array can have several item (here's just 2, but maybe I can have 7 level). I've a lot trouble with this. Then this ID is going to be used as a parameter in a sql request, but this is another story.

This is my array :

Array
        (
            [0] => Array
                (
                    [0] => Array
                        (
                            [id] => 10
                        )
                    [1] => Array
                        (
                            [id] => 11
                        )
                    [2] => Array
                        (
                            [id] => 12
                        )
                )
            [1] => Array
                (
                    [0] => Array
                        (
                            [id] => 11
                        )
                    [1] => Array
                        (
                            [id] => 12
                        )
                )
        )

This is my foreach loop :

foreach($dataListe as $listeDiff){
            foreach($listeDiff as $$item){
                // echo $item[0].'<br />';
                echo "<pre>".print_r($item, true)."</pre>";
            }
        }

Result :

        Array
(
    [id] => 10
)

Array
(
    [id] => 11
)

Array
(
    [id] => 12
)

Array
(
    [id] => 11
)

Array
(
    [id] => 12
)

Wanted :

        Array
(
    [id] => 10
)

Array
(
    [id] => 11
)

Array
(
    [id] => 12
)

Upvotes: 1

Views: 65

Answers (2)

Mahesh Hegde
Mahesh Hegde

Reputation: 1209

Following should work

$dataListe = array(
    array(array('id'=>10),array('id'=>20),array('id'=>20),array('id'=>10),array('id'=>20)),
    array(array('id'=>10),array('id'=>30),array('id'=>20),array('id'=>10),array('id'=>20))
    );

$result = array();
foreach($dataListe as $listeDiff){
    foreach($listeDiff as $item){
            if(!(in_array($item, $result))){
               $result[] = $item;
               echo "<pre>".print_r($item, true)."</pre>";
            }

    }   
}

sample out put

Array
(
[0] => Array
    (
        [id] => 10
    )

[1] => Array
    (
        [id] => 20
    )

[2] => Array
    (
        [id] => 30
    )

)

Upvotes: 0

J. Doe
J. Doe

Reputation: 1732

use array_unique()

$result = [];
foreach($dataListe as $listeDiff){
   $result[] = $listeDiff;        
}
$result = array_unique($result);

Upvotes: 1

Related Questions