0

I have an array containing this

Array ( 
[0] => Array ( [0] => Sub1 ) 
[1] => Array ( [0] => Sub1 [1] => Gold ) 
[2] => Array ( [0] => Sub1 [1] => Sub2 ) 
[3] => Array ( [0] => Sub1 [1] => Sub2 [2] => Sub3 ) 
[4] => Array ( [0] => Sub1 [1] => Sub2 [2] => Sub3 [3] => Sub4 ) 
[5] => Array ( [0] => Sub1 [1] => Test ) 
)

How can i remove the array [2] [3] as they are existent in [4]

and the array would be like

Array (  
[0] => Array ( [0] => Sub1 [1] => Gold )  
[1] => Array ( [0] => Sub1 [1] => Sub2 [2] => Sub3 [3] => Sub4 ) 
[2] => Array ( [0] => Sub1 [1] => Test ) 
)

Is it possible to automate?

3
  • use array_intersect php.net/manual/en/function.array-intersect.php function Commented Apr 19, 2014 at 15:34
  • @Alex - From what I can see of array intersect it return only the values existing in multiple arrays, I want the opposite of that. to remove the repeated values, that already exist in the array. Imagine it like a path or a url string like for example Sub1/Sub2 Sub1/Sub2/Sub3 and Sub1/Sub2/Sub3/Sub4 Commented Apr 19, 2014 at 15:44
  • 1
    [0] appears in all other ones too. Commented Apr 19, 2014 at 15:45

1 Answer 1

2
$result = array();
foreach ($original as $orig_el) {
    $found = false;
    foreach ($result as &$new_el) {
        if (count($orig_el) >= count($new_el) && array_slice($orig_el, 0, count($new_el)) == $new_el) {
            $new_el = $orig_el;
            $found = true;
            break;
        }
    }
    if (!$found) {
        $result[] = $orig_el;
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

The array stays the same after going through the code you gave here, I tried it and it outputs the same structure as the input.
Can you make a demo at IDEone.com?
Made the example, and it's working, I had a typo, Thank you so much! here is the example btw link

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.