[英]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. 例如,我可以使用上述方法通过
alpha2 = ad
查找此数组。 But what i need is the possibility to search for eur IN currencies
for example. 但是我需要的是例如搜索
eur IN currencies
的可能性。
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. 因为
eur
不是主要currencies
的价值,但是它是子密钥的价值。
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.