Created
October 8, 2025 05:59
-
-
Save jalallinux/1aa34f45e79740221b6b3da8080362e3 to your computer and use it in GitHub Desktop.
Search on JSON with a special conversion
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 | |
| if (! function_exists('json_get')) { | |
| /** | |
| * Get value from JSON array using dot notation or array search | |
| * | |
| * @param array $data JSON data | |
| * @param string $path Path like "current.geram24" or "gold.*.symbol:IR_GOLD_18K" | |
| * @return mixed | |
| */ | |
| function json_get(array $data, string $path): mixed | |
| { | |
| $parts = explode('.', $path); | |
| $current = $data; | |
| foreach ($parts as $index => $part) { | |
| // Check if this is wildcard (*) | |
| if ($part === '*') { | |
| // Get the next part which should have search syntax | |
| $nextPart = $parts[$index + 1] ?? null; | |
| if ($nextPart && str_contains($nextPart, ':')) { | |
| [$searchKey, $searchValue] = explode(':', $nextPart, 2); | |
| // Search in array | |
| if (! is_array($current)) { | |
| return null; | |
| } | |
| $found = null; | |
| foreach ($current as $item) { | |
| if (is_array($item) && isset($item[$searchKey]) && $item[$searchKey] == $searchValue) { | |
| $found = $item; | |
| break; | |
| } | |
| } | |
| $current = $found; | |
| // Skip the next part since we already processed it | |
| next($parts); | |
| } | |
| } elseif (str_contains($part, ':')) { | |
| // Skip if already processed by wildcard | |
| continue; | |
| } else { | |
| // Simple key access | |
| if (! isset($current[$part])) { | |
| return null; | |
| } | |
| $current = $current[$part]; | |
| } | |
| } | |
| return $current; | |
| } | |
| } |
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
| { | |
| "gold": [ | |
| { | |
| "date": "1404/07/15", | |
| "time": "19:59", | |
| "time_unix": 1759854594, | |
| "symbol": "IR_GOLD_18K", | |
| "name_en": "18K Gold", | |
| "name": "طلای 18 عیار", | |
| "price": 10929900, | |
| "change_value": 399000, | |
| "change_percent": 3.79, | |
| "unit": "تومان" | |
| } | |
| ], | |
| "current": { | |
| "geram24": { | |
| "p": "145,730,000", | |
| "h": "146,752,000", | |
| "l": "140,402,000", | |
| "d": "0", | |
| "dp": 0, | |
| "dt": "", | |
| "t": "۱۵ مهر", | |
| "t_en": " 7 Oct", | |
| "t-g": "۱۵ مهر", | |
| "ts": "2025-10-07 00:00:00" | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment