Created
August 16, 2026 17:49
-
-
Save collei/1597d3a5bb890429241abb8ca29e5cba to your computer and use it in GitHub Desktop.
helpers.php
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
| <?php | |
| /** | |
| * Retrieves data from nested structures (array/object) with '.' notation. | |
| * Implemented using while loop. | |
| * | |
| * @param array|object $data | |
| * @param string $name | |
| * @return mixed | |
| */ | |
| function get_nested_data_from($data, string $name) | |
| { | |
| while (is_array($data) || is_object($data)) { | |
| list($name, $further) = (stripos($name,'.') !== false) | |
| ? explode('.', $name, 2) | |
| : array($name, null); | |
| if (is_array($data) && is_numeric($name)) { | |
| $name = (int) (float) $name; | |
| } | |
| if (is_array($data)) { | |
| if (array_key_exists($name, $data)) { | |
| $data = $data[$name]; | |
| } else { | |
| return null; | |
| } | |
| } elseif (is_object($data)) { | |
| if (property_exists($data, $name)) { | |
| $data = $data->$name ?? null; | |
| } else { | |
| return null; | |
| } | |
| } | |
| if (empty($further)) { | |
| return $data; | |
| } | |
| $name = $further; | |
| } | |
| return $data; | |
| } | |
| /** | |
| * Retrieves data from nested structures like arrays and data objects | |
| * (such those extracted from JSON). Accepts '.' notation. | |
| * Implemented using recursion. | |
| * | |
| * @param mixed $data | |
| * @param string $name | |
| * @param mixed $default = null | |
| * @return mixed | |
| */ | |
| function recursively_get_nested_data_from($data, string $name, $default = null) | |
| { | |
| list($here, $further) = (stripos($name,'.') !== false) | |
| ? explode('.', $name, 2) | |
| : array($name, null); | |
| if (is_numeric($here)) { | |
| $here = (int) (float) $here; | |
| } | |
| if (empty($further)) { | |
| if (is_array($data) && array_key_exists($here, $data)) { | |
| return $data[$here] ?? $default ?? null; | |
| } | |
| if (is_object($data) && property_exists($data, $here)) { | |
| return $data->$here ?? $default ?? null; | |
| } | |
| return $default ?? null; | |
| } | |
| if (is_array($data) && array_key_exists($here, $data)) { | |
| return get_nested_data_from($data[$here], $further); | |
| } | |
| if (is_object($data) && property_exists($data, $here)) { | |
| return get_nested_data_from($data->$here, $further); | |
| } | |
| return $default ?? null; | |
| } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment