I have a multidimensional array whose depth is uncertain or let’s say depends on how many categories & sub-categories(& sub-sub-categories) are there in magento website, as I calling function $product->getCategoryIds()
.
Now let’s assume I get all product’s(that are added in the cart/checkout) category tree-hierarchy as multidimensional array like below:
Array
(
[0] => Array
(
[0] => 40
)
[1] => Array
(
[0] => 40
)
[2] => Array
(
)
[3] => Array
(
)
[4] => Array
(
[0] => 16
)
[5] => Array
(
[0] => 16
)
)
But as it is an ecomerce site’s category heirarchy, you can safely imagine, site could have any depth of categories, sub-categories, sub-sub-categories and so on. Unknown hierarchy of product categories so unknown depth of category ids array.
Now comes my confusion and query, how to check if every sub-array and/or sub-sub-array contains a particular category Id(eg. 40 or 16) or not, by using a combination of various php array functions and using as less loops as possible ?
All I can think of is nested for/foreach
loops which has performance overheads, so I am looking for better alternatives to that.
3
Answers
It sounds like you are looking for something like this:
You can use array_filter() to remove empty categories from the array
I prefer using recursion when you are not certain about the input(the structure of the array)
you can use something like this
Example usage
this outputs
live demo (https://eval.in/835973);