php中數(shù)組的搜索程序代碼
來源:程序員人生 發(fā)布時(shí)間:2014-01-07 09:43:37 閱讀次數(shù):2725次
在php中簡(jiǎn)單數(shù)據(jù)搜索很簡(jiǎn)單我們直接使用in_array() 函數(shù)在數(shù)組中搜索給定的值即可,這種是簡(jiǎn)單的一維數(shù)據(jù),例如下代碼:
- <?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()函數(shù)
如果在一個(gè)數(shù)組中找到一個(gè)指定的鍵,函數(shù)array_key_exists()返回true,否則返回false,其形式如下:
boolean array_key_exists(mixed key,array array);
下面的例子將在數(shù)組鍵中搜索apple,如果找到,將輸出這個(gè)水果的顏色,代碼如下:
- $fruit["apple"] = "red";
- $fruit["banana"] = "yellow";
- $fruit["pear"] = "green";
- if(array_key_exists("apple", $fruit)){
- printf("apple's color is %s",$fruit["apple"]);
- }
執(zhí)行這段代碼得到的結(jié)果:apple's color is red
array_search()函數(shù),代碼如下:
- $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])
array_keys()函數(shù),代碼如下:
- $fruits["apple"] = "red";
- $fruits["banana"] = "yellow";
- $fruits["watermelon"]="green";
- $keys = array_keys($fruits);
- print_r($keys);
上面的方法都只能搜索一維數(shù)據(jù),如果是多維數(shù)據(jù)就沒辦法了,php搜索多維數(shù)組的鍵值,如下面例子:
- $foo[1]['a']['xx'] = 'bar 1';
- $foo[1]['b']['xx'] = 'bar 2';
- $foo[2]['a']['bb'] = 'bar 3';
- $foo[2]['a']['yy'] = 'bar 4';
- $foo[3]['c']['dd'] = 'bar 3';
- $foo[3]['f']['gg'] = 'bar 3';
- $foo['info'][1] = 'bar 5';
如果要查找 bar 3 怎么進(jìn)行查找呢,有三個(gè)結(jié)果,而這三個(gè)結(jié)果都要,看下面的函數(shù):
- function array_search_re($needle, $haystack, $a=0, $nodes_temp=array()){
- global $nodes_found;
- $a++;
- foreach ($haystack as $key1=>$value1) {
- $nodes_temp[$a] = $key1;
- if (is_array($value1)){
- array_search_re($needle, $value1, $a, $nodes_temp);
- }
- else if ($value1 === $needle){
- $nodes_found[] = $nodes_temp;
- }
- }
- return $nodes_found;
- }
這個(gè)函數(shù)就可以把上面要查找到的內(nèi)容全部返回出鍵名來,代碼如下:
- $result = array_search_re('bar 3', $foo);
- print_r($result);
-
- Array ( [0] => Array ( [1] => 2 [2] => a [3] => bb )
- [1] => Array ( [1] => 3 [2] => c [3] => dd )
- [2] => Array ( [1] => 3 [2] => f [3] => gg )
- )
php搜索多維數(shù)組的鍵名,代碼如下:
- function array_search_key($needle, $haystack){
- global $nodes_found;
- foreach ($haystack as $key1=>$value1) {
-
- if ($key1=== $needle){
-
- $nodes_found[] = $value1;
-
- }
- if (is_array($value1)){
- array_search_key($needle, $value1);
- }
-
-
- }
- return $nodes_found;
- }
- $result = array_search_key('a', $foo);
- print_r($result);
輸出結(jié)果為如下:
- Array
- (
- [0] => Array
- (
- [xx] => bar 1
- )
- [1] => Array
- (
- [bb] => bar 3
- )
- [2] => Array
- (
- [yy] => bar 4
- )
- )
通過遍歷我們可以實(shí)現(xiàn)多維數(shù)據(jù)搜索了.
生活不易,碼農(nóng)辛苦
如果您覺得本網(wǎng)站對(duì)您的學(xué)習(xí)有所幫助,可以手機(jī)掃描二維碼進(jìn)行捐贈(zèng)