PHP - 数组搜索获取键值


PHP - array search get key value

>我有一个数组如下,

$country = array ("01. USA","02. Russia","03. UK","04. India");

我只是想用这个字符串$str = "USA";搜索我的数组,它应该向我返回值所在的键。这可能吗。我尝试使用array_search()但它不起作用。

更新:

实际的数组具有,

Array ( [0] => 01. Australian Dollar [1] => 06. Swedish Kroner [2] => 02. British Pound Sterling [3] => 07. Swish Frank [4] => 03. Canadian Dollar [5] => 08. U.S. Dollar [6] => 04. Japanese Yen Per 100 [7] => 09. Euro [8] => 05. Singapore Dollar [9] => 10. Taka Per 100 )

如果包含 strstr(),您可以尝试每个值测试。

    foreach ($country as $n => $state)
    {
        if (strstr($state, 'USA'))
        {
            //found
            break;
        }
    }
$str = 'USA';
foreach ($country as $k => $v) {
  if (strpos($v, $str) !== FALSE)
    break;
}
echo $k; // will print: 0

您在示例中没有设置任何键,这意味着键会自动分配一个介于 0 到 3 之间的值。并且值"USA"在您的数组中不存在,如果您要搜索"01.USA",然后你会得到值 0(零),因为它是数组中第一个带有自动分配键的值。

在此数组上对"USA"执行array_search,它可能会给您预期的结果:

$country = array (1 => "USA", 2 => "Russia", 3 => "UK", 4 => "India");

您需要使用 key => value 来正确分配键和值。除了1 => "USA",您还可以执行"01" => "USA"这将给美国钥匙"01"。

$search = "USA";
$country = array ("01. USA","02. Russia","03. UK","04. India");
foreach($country as $key=>$cnt){
   if(strpos($cnt,$search)){
      echo "String found in position $key";
      break;
   }
 }

您可以通过这种方式编写代码。但是,如果您的搜索字符串也是"US",它也会返回true。

你可以按照preg_grep这里描述的preg-grep使用。

然后,您应该将preg_grep的结果放入array_search。

$results = preg_grep($pattern, $input);
$indices = array();
foreach ($results as $result) {
   $indices[] = array_search($result, $input);
}

如果您希望保持当前结构(这不是最佳解决方案)而没有任何键。以下是您可以执行的操作:

$countries = array (
                    "01. USA",
                    "02. Russia",
                    "03. UK",
                    "04. India"
                   );
$input  =  'UK';
$output =  '';
foreach ($countries as $country){
     $found = strpos($country,$input);
     if ($found > 0){  // assuming $country wouldn't start with country name.
         $output = trim(substr($country,0,$found-1));
         break;
     }
}

但是,我相信每个人都会建议你在数组中使用键。