So I wrote a function that searches two levels deep into an array for a key and subkey pair. Basically it is looking for key['subkey'] and if it finds it, returns key['subkey'].
What I am looking for is a way to do this in a manner that is truly recursive and searches as many levels deep as needed until it either reaches the end of the array and is forced to return false, or finds the value and returns it.
I am completely newbish at PHP, and I have googled for hours with no result. Any pointers in the right direction would be appreciated.
This is the function:
function searchArray($array, $key, $subkey) {
foreach ($array as $item){
if (is_array($item) && isset($item[$key]) && isset($item[$key][$subkey])){
return $item[$key][$subkey];
} else {
foreach ($item as $subitem){
if (is_array($subitem) && isset($subitem[$key]) && isset($subitem[$key][$subkey])){
return $subitem[$key][$subkey];
}
}
}
}
}
Sample Array:
"locales" => array(
"America" => array(
"locations" => array(
"us" => array(
"title" => "United States",
"lang" => "en_US",
),
"gl" => array(
)
)
),
"Europe" => array(
"locations" => array(
"at" => array(
"title" => "Österreich",
"lang" => "de_DE",
),
"fr" => array(
"title" => "France",
"lang" => "fr_FR",
),
"de" => array(
"title" => "Deutschland",
"lang" => "de_DE",
),
"it" => array(
"title" => "Italy",
"lang" => "it_IT",
),
"uk" => array(
"title" => "United Kingdom",
"lang" => "en_GB",
)
)
),
"Africa" => array(
"locations" => array(
"za" => array(
"title" => "Südafrika",
"lang" => "en_ZA",
)
)
),
"Asia & Pacific" => array(
"locations" => array(
"au" => array(
"title" => "Australia",
"lang" => "en_AU",
),
"cn" => array(
"title" => "中国",
"lang" => "zh_CN",
),
"hk" => array(
"title" => "香港",
"lang" => "zh_CN",
),
"jp" => array(
"title" => "日本",
"lang" => "jp_JP",
),
"kr" => array(
"title" => "한국",
"lang" => "ko_KR",
)
)
)
)
calling searchArray($siteOptions['locales'], 'us', 'lang') should return 'en_US'.
1 Answer