Home  >  Article  >  Backend Development  >  php中怎么搜索相关联数组键值及获取之_PHP

php中怎么搜索相关联数组键值及获取之_PHP

WBOY
WBOYOriginal
2016-06-01 11:59:21875browse

1.搜索关联数组键
如果在一个数组中找到一个指定的键,函数array_key_exists()返回TRUE,否则返回FALSE。其

形式如下:
boolean array_key_exists(mixed key, array array)

下面的例子将在数组键中搜索Ohio,如果找到,将输出这个州加入美国联邦政府的育关信息:
$state["Delaware"]="December 7,1787";
$state["Pennsylvania"]="December 12, 1787";
$state["Ohio"]="March l,1803";
86 第5章数 组
if (array_key_exists("Ohio", $state》
printf("Ohio joined the Union on %s", $state["Ohio"]);
结果如下:

2.搜索关联数组值
array_search()函数在一个数组中搜索一个指定的值,如果找到则返回相应的键,否则返回FALSE。

其形式如下:
下面的例子在$state中搜索一个特定的日期(December7),如果找到,则返回相应州的有关信息:
$state["Ohio"] = "March l"; .
$statef"Delaware"l = "December 7";
$state["Pennsylvania"] = "December 12u;
$founded = array_search("December 7", $state),
i+ ($founded) printf("%s was founded on %s.", $founded, $state[$founded]);
输出如下:
Delaware was十ounded on December 7.

5.4.2获取数组键
array_keys()函数返回一个数组,其中包含所搜索数组中找到的所有键。其形式知下:
array array_keys(array array【J mixed search_value])
如果包含可选参数search value,则只会返回与该值匹配的键。下面的例子将输出$state数组中
找到的所有键值:
$state["Delaware"] = "December 7, 1787";
$state["Pennsylvania"] = "December 12, i787";
$state["New Jersey"] = "December 18, 1787";
$keys = array_keys($state);
print_r($keys);
输出如下:

5.4.3获取数组值
array_values()函数返回一个数组中的所有值,并自动为返回的数组提供数值索引。其形式如下:
array array_values(array array)

5.5遍历数组 87
下面的例子将获取$population中找到的各州人口数:
$population=array("Ohio"=>"11,421,267", "Iowa"=>"2,936,760");
print_r(array_values($population》;
这个例子的输出如下:

5.5遍历数组
通常需要遍历数组并获得各个键或值(或者同时获得键和值),所以毫不奇怪,PHP为此提供了
一些函数来满足需求。许多函数能完成两项任务,不仅能获取当前指针位置的键或值,还能将指针移
向下一个适当的位置。本节将介绍这些函数。

5.5.1 获取当前数组键
key()函数返回input_array中当前指针所在位置的键。其形式如下:
mixed key(array array)

下面的例子通过迭代处理数组并移动指针来输出$capitals数组的键:
$capitals=array("Ohio"=>"Columbus", "Iowa"=>"Des Moines");
echo "

Can you name the capitals of these states?

";
while($key=key($capitals》{
printf("%s
“,$key);
next($capitals);

将返回以下结果:
Ohio
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn