3v4l.org

run code in 300+ PHP versions simultaneously
<?php $input = [ 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], ], ] ]; function array_filter_clean(array $array, array $callbacks, $currentDepth = 0, $currentKey = '') { if (array_key_exists($currentDepth, $callbacks)) { // identify node to apply callback to $callback = $callbacks[$currentDepth]; if (!$callback($currentKey, $array)) { // empty node when callback returns false (or falsy) return []; } } foreach ($array as $key => &$value) { // &value to modify $array if (is_array($value)) { $value = array_filter_clean($value, $callbacks, $currentDepth+1, $key); // recurse if array } } return array_filter($array); // remove empty nodes (you may want to add "afterCallbacks" here) } $callbacksByDepth = [ /* 2 => function ($key, $value) { return $key > 20; }, */ 3 => function ($key, $value) { return $value['res_id']%2; }, ]; $output = array_filter_clean($input, $callbacksByDepth); print_r($output);

preferences:
15.36 ms | 405 KiB | 5 Q