php 中数组的搜索程序代码
在
php 中简单数据搜索很简单我们直接使用 in_array() 函数在数组中搜索给定的值即可,这
种是简单的一维数据
例
代码如下
<?php
$people = array("Peter", "Joe", "Glenn", "Cleveland");
if (in_array("Glenn",$people))
{
echo "Match found";
}
else
{
echo "Match not found";
}
?>
输出:
Match found。
array_key_exists()函数
如果在一个数组中找到一个指定的键,函数
array_key_exists()返回 true,否则返回 false。其
形式如下:
1 boolean array_key_exists(mixed key,array array);
下面的例子将在数组键中搜索
apple,如果找到,将输出这个水果的颜色:
代码如下
1 $fruit["apple"] = "red";
2 $fruit["banana"] = "yellow";
3 $fruit["pear"] = "green";
4 if(array_key_exists("apple", $fruit)){
5 printf("apple's color is %s",$fruit["apple"]);
6 }
执行这段代码得到的结果:
1 apple's color is red
array_search()函数
代码如下
$fruits["apple"] = "red";
$fruits["banana"] = "yellow";
$fruits["watermelon"]="green";
$founded = array_search("green", $fruits);
if($founded)
printf("%s was founded on %s.",$founded, $fruits[$founded])