Last active
September 26, 2020 01:08
-
-
Save savasdersimcelik/fdf51fb00a81f68e2b8db28eb52caec3 to your computer and use it in GitHub Desktop.
PHP JSON Deep Search | Returns the value of an element with a key value in an json of uncertain depth.
This file contains 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
if (! function_exists('json_deep_search')) | |
{ | |
/** | |
* Author : Savaş Dersim ÇELİK | |
* Returns the value of an element with a key value in an json of uncertain depth. | |
* | |
* @param json $json | |
* @param string $key | |
* | |
* @return mixed|false | |
*/ | |
function json_deep_search($json, string $key) | |
{ | |
$array = json_decode($json, true); | |
if (is_array($array)) { | |
if (isset($array[$key])) { | |
return $array[$key]; | |
}else{ | |
foreach ($array as $value) { | |
if (is_array($value)) { | |
$result = json_deep_search(json_encode($value), $key); | |
if ($result) { | |
return $result; | |
} | |
} | |
} | |
} | |
} | |
return false; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment