Note
This question is NOT a duplicate of
or several other related questions
I have a very peculiar use case where I have to filter a multi-dimensional array 'inwards to outwards', implying
"filter the innermost level elements, then it's preceding level elements and so on until coming to filtering the topmost level"
As an (dummy, mock) example, consider this
suppose we have a nested of restaurant-ids (res_ids) grouped by countries (1, 2, & 3) & cities (11, 12, 21, 22, 23, 31)
[
1 => [
11 => [
111 => ['res_id' => 111, 'city_id' => 11, 'country_id' => 1],
112 => ['res_id' => 112, 'city_id' => 11, 'country_id' => 1],
113 => ['res_id' => 113, 'city_id' => 11, 'country_id' => 1],
],
12 => [
121 => ['res_id' => 121, 'city_id' => 12, 'country_id' => 1],
],
],
2 => [
21 => [
212 => ['res_id' => 212, 'city_id' => 21, 'country_id' => 2],
214 => ['res_id' => 214, 'city_id' => 21, 'country_id' => 2],
],
22 => [
221 => ['res_id' => 221, 'city_id' => 22, 'country_id' => 2],
222 => ['res_id' => 222, 'city_id' => 22, 'country_id' => 2],
223 => ['res_id' => 223, 'city_id' => 22, 'country_id' => 2],
],
],
3 => [
31 => [
312 => ['res_id' => 312, 'city_id' => 21, 'country_id' => 2],
314 => ['res_id' => 314, 'city_id' => 21, 'country_id' => 2],
],
]
]
- and we want to remove all restaurants (plus the parent sub-array structure) having even res_ids (keep odd ones)
- so that resulting output nested array is as follows
- note that not only individual 'leaf' items depicting res have been filtered, but also higher level city and country items have been filtered if they contained only even res_ids (which we intended to remove)
[
1 => [
11 => [
111 => ['res_id' => 111, 'city_id' => 11, 'country_id' => 1],
113 => ['res_id' => 113, 'city_id' => 11, 'country_id' => 1],
],
12 => [
121 => ['res_id' => 121, 'city_id' => 12, 'country_id' => 1],
],
],
2 => [
22 => [
221 => ['res_id' => 221, 'city_id' => 22, 'country_id' => 2],
223 => ['res_id' => 223, 'city_id' => 22, 'country_id' => 2],
],
],
]
actually i myself created above array from a flat array by recursive grouping; but now I have to filter them in groups (which can't be done before grouping)
- While i can certainly do this using nested loops, I was wondering if we can create a generic function for it (i have other such multi-dimensional filtering use-cases at different depths across my project)
- Another important thing to note here that given the generic filtering criteria requirement, we would ideally like to be able to have a different filtering criteria per level: custom functions per se.
Any ideas?