1
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
    )

)
3
  • 3
    what have you tried? Can you show us (code) where you run in to trouble? Commented Oct 10, 2017 at 18:33
  • What if the last array contained 4943 instead of 108. What should the behavior be? Should that array be removed? Commented Oct 10, 2017 at 18:57
  • The original arrays are made from all the categories each item belongs to, I have then requested all the ancestors to each id and added them to the array, so the last array can not contain only 4943 ``` foreach ($product_cat as $cat ) { $simple_cats[] = array ( 'parent_id' => $cat->parent, 'id' => $cat->term_id, 'acestors' => get_ancestors( $cat->term_id, 'product_cat' ) ); } foreach ($simple_cats as &$cat ) { $cat['ids'] = array_reverse( $cat['acestors'] ); array_push($cat['ids'], $cat['id']); $cat_ids[] = $cat['ids']; } ``` Commented Oct 10, 2017 at 19:18

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

Comments

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.