Last active
August 7, 2017 07:09
-
-
Save nmfzone/7931deb2153da292aca0eab0ed2f789b to your computer and use it in GitHub Desktop.
Dynamically remove very nested array by key. This can remove key in array, no matter how deep It was.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * Unset given key from array. | |
| * | |
| * @param array $array | |
| * @param mixed $parents | |
| * @param string $glue | |
| * @return void | |
| */ | |
| function array_unset_value(&$array, $parents, $glue = '.') | |
| { | |
| if (!is_array($parents)) { | |
| $parents = array_filter(explode($glue, $parents), 'strlen'); | |
| } | |
| $key = array_shift($parents); | |
| if (empty($parents)) { | |
| unset($array[$key]); | |
| } elseif (is_array($array) && array_key_exists($key, $array)) { | |
| if (!is_array($array[$key])) { | |
| array_unset_value($array[$key], $parents); | |
| } elseif (array_key_exists(0, $array[$key])) { | |
| foreach ($array[$key] as &$arr) { | |
| $arrr = isset($arr[$key]) && is_array($arr[$key]) ? $arr[$key] : $arr; | |
| array_unset_value($arrr, $parents); | |
| $arr = $arrr; | |
| } | |
| } else { | |
| array_unset_value($array[$key], $parents); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment