简体   繁体   中英

PHP Extend array search function

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?

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM