Reputation: 361
I am currently using this method to find arrays by keys + values:
public static function getCountryDataByVal($array, $key, $value, &$results = array()) {
if (!is_array($array)) {
return;
}
if (isset($array[$key]) && $array[$key] == $value) {
$results[] = $array;
}
foreach ($array as $subarray) {
self::getCountryDataByVal($subarray, $key, $value, $results);
}
return $results;
}
This works fine so far, but there's a problem and i have no idea how to solve it. Let's assume, that i have this array structure:
array(8) {
["alpha2"]=>
string(2) "ad"
["alpha3"]=>
string(3) "and"
["numeric3"]=>
string(3) "020"
["callingCodes"]=>
array(1) {
[0]=>
string(3) "376"
}
["tlds"]=>
array(1) {
[0]=>
string(2) "ad"
}
["currencies"]=>
array(1) {
[0]=>
string(3) "eur"
}
["longitude"]=>
string(4) "42.5"
["latitude"]=>
string(3) "1.5"
}
I can use the method above to find this array by alpha2 = ad
for example. But what i need is the possibility to search for eur IN currencies
for example.
Using this does not work:
getCountryDataByVal($array, 'currencies', 'eur');
because eur
is not the value of the key currencies
, but it's the value of a subkey.
Any idea, how i have to extend the method above to achieve this?
Upvotes: 0
Views: 116
Reputation: 1631
try that function:
public static function getCountryDataByVal($array, $key, $value, &$results = array()) {
if (!is_array($array)) {
return;
}
if ((isset($array[$key]) && $array[$key] == $value )||
(isset($array[$key]) && is_array($array[$key]) && array_search($value, $array[$key]) !== FALSE ) )
{
$results[] = $array;
}
foreach ($array as $subarray) {
self::getCountryDataByVal($subarray, $key, $value, $results);
}
return $results;
}
Upvotes: 1