php 使用键查找数组值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2970768/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 08:17:43  来源:igfitidea点击:

Find array value using key

phparrayskey

提问by JEagle

I would like to find the value in an array using the key.

我想使用键在数组中找到值。

like this:

像这样:

$array=('us'=>'United', 'ca'=>'canada');
$key='ca';

How can i have the value 'canada'? thanks.

我怎么能拥有“加拿大”的价值?谢谢。

回答by HoLyVieR

It's as simple as this :

就这么简单:

$array[$key];

回答by Mark Rushakoff

It looks like you're writing PHP, in which case you want:

看起来您正在编写 PHP,在这种情况下,您需要:

<?
$arr=array('us'=>'United', 'ca'=>'canada');
$key='ca';
echo $arr[$key];
?>

Notice that the ('us'=>'United', 'ca'=>'canada')needs to be a parameter to the array functionin PHP.

请注意,('us'=>'United', 'ca'=>'canada')需要是PHP 中数组函数的参数。

Most programming languages that support associative arrays or dictionaries use arr['key']to retrieve the item specified by 'key'

大多数支持关联数组或字典的编程语言arr['key']用于检索由'key'

For instance:

例如:

Ruby

红宝石

ruby-1.9.1-p378 > h = {'us' => 'USA', 'ca' => 'Canada' }
 => {"us"=>"USA", "ca"=>"Canada"} 
ruby-1.9.1-p378 > h['ca']
 => "Canada" 

Python

Python

>>> h = {'us':'USA', 'ca':'Canada'}
>>> h['ca']
'Canada'

C#

C#

class P
{
    static void Main()
    {
        var d = new System.Collections.Generic.Dictionary<string, string> { {"us", "USA"}, {"ca", "Canada"}};
        System.Console.WriteLine(d["ca"]);
    }
}

Lua

路亚

t = {us='USA', ca='Canada'}
print(t['ca'])
print(t.ca) -- Lua's a little different with tables