Michael Compton
Michael Compton

Reputation: 53

php array of arrays remove array containing matching collection of values

Array
(
  [0] => Array
    (
        [0] => 4937
    )

  [1] => Array
    (
        [0] => 4937
        [1] => 4941
    )

  [2] => Array
    (
        [0] => 4937
        [1] => 5610
    )

  [3] => Array
    (
        [0] => 4937
        [1] => 5610
        [2] => 4943
    )

  [4] => Array
    (
        [0] => 108
    )

)

Each array is a list of categories followed by its sub categories and sub sub categories. I want to show only original patterns of numbers. so I want to remove array 2 because that pattern of numbers already exists in array 3, but I want keep array 1 because the number that follows 4937 is different to array 3. The end result should be this,

Array
(

  [1] => Array
    (
        [0] => 4937
        [1] => 4941
    )

  [3] => Array
    (
        [0] => 4937
        [1] => 5610
        [2] => 4943
    )

  [4] => Array
    (
        [0] => 108
    )

)

Upvotes: 1

Views: 64

Answers (1)

vstelmakh
vstelmakh

Reputation: 772

If you do not have multiple parents for child categories, try this:

for($i = 1; $i < count($array); $i++){
    end($array[$i-1]);
    $k = key($array[$i-1]);
    if ($array[$i-1][$k] == $array[$i][$k]) {
        unset($array[$i-1]);
    }
}
$array = array_values($array); // reindex array if you need

Upvotes: 2

Related Questions