我有一个多维国家/地区数组,其中包含:
针是 countryCode 并且干草堆 $ countriesArray 。您将如何搜索字符串(countryCode)并返回相应的名称和标志。这个数组是否构造错误?。
阵列
$CountriesArray = array(array( code => "bj",
name => "Benin",
flag => "flag flag-bj"
),
array( code => "bw",
name => "Botswana",
flag => "flag flag-bw"
),
array( code => "cg",
name => "Congo",
flag => "flag flag-cg"
)
ect....
);
ANSWER -Array格式更新,其中键是countryCode
$CountriesArray = array( array( bj => array( name=> "Benin", flag => "flag flag-bj" )),
array( bw => array( name=> "Botswana", flag => "flag flag-bw" )),
array( cg => array( name=> "Congo", flag => "flag flag-cg" ))
);
搜索数组,其中$ n =针
function multiDimenArraySearch($n,$h){
foreach($h as $key => $value){
if($key == $n) return $value;
}
}
$n = "bj";
$search = multiDimenArraySearch($n,$CountriesArray);
$name = $search[$n]["name"]; //outputs name
$flag = $search[$n]["flag"]; // outputs flag class
答案 0 :(得分:1)
相同的问题here,基本上你只需循环遍历所有不同的数组。在下面的示例中,$ return_val将是该国家/地区的数组。
$search_term = 'cg';
foreach($countriesArray as $c_info){
if($c_info['code']==$search_term){
$return_val = $c_info;
}
}
答案 1 :(得分:0)
for($i = 0; $i <= count($countriesArray); $i++){
if($countriesArray[$i]["code"] == "cg"){
return $countriesArray[$i]["name"];
}
}
这应该有效
foreach版本:
foreach($countriesArray as $country){
if($country["code"] == "cg"){
...
}
}
示例功能:
function multiDimenArraySearch($n,$h){
foreach($h as $arr){
if($arr['code'] == $n){
return $arr;
}
}
}
$search = multiDimenArraySearch("cg",$countriesArray);
$name = $search["name"];
对于搜索值,是数组键:
foreach($h as $key => $value){
if($key == "cg") return $value;
}