简体   繁体   中英

php- multidimensional array search

I have a multidimensional countries array containing :

  • code -> Country Code
  • name - > Country Name
  • flag -> CSS sprite flag class

The needle is a countryCode and haystack the $countriesArray . How would you search for a string(countryCode) and return the corresponding name and flag. Is this array badly constructed?.

Array

$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 format updated where the key is the 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" ))
                   );

Search array where $n = needle

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

Same question over here , basically you just have to loop through all the different arrays. In the example below $return_val will be the array of the country.

$search_term = 'cg';
foreach($countriesArray as $c_info){
   if($c_info['code']==$search_term){
      $return_val = $c_info;
   }
}
for($i = 0; $i <= count($countriesArray); $i++){
    if($countriesArray[$i]["code"] == "cg"){
        return $countriesArray[$i]["name"];
    }
}

this should work

foreach version:

foreach($countriesArray as $country){
    if($country["code"] == "cg"){
        ...
    }
}

Example function:

function multiDimenArraySearch($n,$h){
    foreach($h as $arr){
        if($arr['code'] == $n){
            return $arr;
        }
    }
}

$search = multiDimenArraySearch("cg",$countriesArray);
$name = $search["name"];

For search value is array key:

foreach($h as $key => $value){
    if($key == "cg") return $value;
}

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