php中數組的搜索程序代碼
來源:程序員人生 發布時間:2014-01-07 09:43:37 閱讀次數:2714次
在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,其形式如下:
boolean array_key_exists(mixed key,array array);
下面的例子將在數組鍵中搜索apple,如果找到,將輸出這個水果的顏色,代碼如下:
- $fruit["apple"] = "red";
- $fruit["banana"] = "yellow";
- $fruit["pear"] = "green";
- if(array_key_exists("apple", $fruit)){
- printf("apple's color is %s",$fruit["apple"]);
- }
執行這段代碼得到的結果: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])
array_keys()函數,代碼如下:
- $fruits["apple"] = "red";
- $fruits["banana"] = "yellow";
- $fruits["watermelon"]="green";
- $keys = array_keys($fruits);
- print_r($keys);
上面的方法都只能搜索一維數據,如果是多維數據就沒辦法了,php搜索多維數組的鍵值,如下面例子:
- $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 怎么進行查找呢,有三個結果,而這三個結果都要,看下面的函數:
- 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;
- }
這個函數就可以把上面要查找到的內容全部返回出鍵名來,代碼如下:
- $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搜索多維數組的鍵名,代碼如下:
- 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);
輸出結果為如下:
- Array
- (
- [0] => Array
- (
- [xx] => bar 1
- )
- [1] => Array
- (
- [bb] => bar 3
- )
- [2] => Array
- (
- [yy] => bar 4
- )
- )
通過遍歷我們可以實現多維數據搜索了.
生活不易,碼農辛苦
如果您覺得本網站對您的學習有所幫助,可以手機掃描二維碼進行捐贈