English 中文(简体)
与数组有问题(_S)(_S)
原标题:Issues with array_search
  • 时间:2012-05-25 18:45:55
  •  标签:
  • php

当我运行以下操作时,我得到的有 < code> B.C. ,但我正在尝试获得 < code> BC BC 。

我设置了 arary_search 来进行严格的比较, 为什么它不返回 "BC" ?

如果我通过“Alberta”,我就会得到“AB”,这是正确的。

<?
function cleanProvince($province)
{
    $values = array(
         AB  =>  Alberta ,
         BC  =>  B.C. ,
         BC  =>  British Columbia ,
         ON  =>  Ontario ,
         ON  =>  Onatrio ,
         ON  =>  Ont ,
         NS  =>  Nova Scotia ,
         QC  =>  Quebec 
    );
    if ($key = array_search(@$province, $values, true)) {
        return $key;
    } else {
        return $province;
    }
}
echo (cleanProvince("B.C."));
?>
最佳回答

您无法在一个数组中拥有多个密钥。 当您这样做时, 第二个密钥将超越第一个密钥 。

$values = array(
     AB => Alberta ,
     BC => B.C. ,
     BC => British Columbia , # Overrides  B.C. 
     ON => Ontario ,
     ON => Onatrio , # Overrides  Ontario 
     ON => Ont , # Overrides  Onatrio 
     NS => Nova Scotia ,
     QC => Quebec ,
);

您再次通过 "B.C." 。 cleanProvince 。 这不是在 $values , 所以 alaray_search 返回 false , 因此 cleanProvince 返回 \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\

问题回答

如所建议,交换您的键和值将产生预期的结果,并避免拨打 arary_search () ,我只能假定这个电话的间接费用要高得多(在大多数情况下,moot点,但如果迭代调用... )。

function getProvince($name){
    $values = array(
         Onatrio  =>  ON ,
         Ontaroi  =>  ON ,
         O.N.  =>  ON ,
        // ...
    );
    return isset($values[$name]) 
        ? $values[$name] 
        : $name; // or null I suppose
}




相关问题
Brute-force/DoS prevention in PHP [closed]

I am trying to write a script to prevent brute-force login attempts in a website I m building. The logic goes something like this: User sends login information. Check if username and password is ...

please can anyone check this while loop and if condition

<?php $con=mysql_connect("localhost","mts","mts"); if(!con) { die( unable to connect . mysql_error()); } mysql_select_db("mts",$con); /* date_default_timezone_set ("Asia/Calcutta"); $date = ...

定值美元

如何确认来自正确来源的数字。

Generating a drop down list of timezones with PHP

Most sites need some way to show the dates on the site in the users preferred timezone. Below are two lists that I found and then one method using the built in PHP DateTime class in PHP 5. I need ...

Text as watermarking in PHP

I want to create text as a watermark for an image. the water mark should have the following properties front: Impact color: white opacity: 31% Font style: regular, bold Bevel and Emboss size: 30 ...

How does php cast boolean variables?

How does php cast boolean variables? I was trying to save a boolean value to an array: $result["Users"]["is_login"] = true; but when I use debug the is_login value is blank. and when I do ...