array_search()函数不搜索数组内的值

时间:2014-12-15 10:24:06

标签: php arrays

我希望该进程包含具有国家名称,拨号代码等的country数组。 以下是我的代码。我想要d_code变量中所有相应国家的$countryName

$countries = array();
$countries[] = array("code"=>"IN","name"=>"India","d_code"=>"+91");
$countries[] = array("code"=>"CA","name"=>"Canada","d_code"=>"+1");

if(search_array("$countryName",$countries));

3 个答案:

答案 0 :(得分:5)

您可以使用array_filter的闭包:

$countries = array();
$countries[] = array("code" => "IN", "name" => "India", "d_code" => "+91");
$countries[] = array("code" => "CA", "name" => "Canada", "d_code" => "+1");

$countries; // your array
$country_name = 'India'; // the value you are looking for
$filtered_array = array_filter($countries, function ($element) use ($country_name) {
    if ($element['name'] === $country_name) return $element['d_code'];
});

$filtered_array; //loop through this array for fields you want

答案 1 :(得分:1)

在数组上循环。您的$countries数组包含数组:

$countries = array();
$countries[] = array("code" => "IN", "name" => "India", "d_code" => "+91");
$countries[] = array("code" => "CA", "name" => "Canada", "d_code" => "+1");

var_dump(searchCountry("India", $countries));

function searchCountry($search, $countries) {
    foreach ($countries as $country) {
        if ($country['name'] == $search) {
            return $country['d_code'];
        }
    }
    return false;
}

答案 2 :(得分:1)

<?php
    $countries = array();
    $countries[] = array("code"=>"IN","name"=>"India","d_code"=>"+91");
    $countries[] = array("code"=>"CA","name"=>"Canada","d_code"=>"+1");
    $d_code = search_array($countryName,$countries);
?>

您的search_array功能可以是这样的

<?php
    function search_array($countryName,$countries){
        foreach($countries as $country){
            if($country["name"] == $countryName){
                return $country["d_code"];
            }
        }
    }
?>