我從xml的webservice轉換了這個數組。我在這個數組中有500個項目。 我想搜索任何值並返回所有找到的具有密鑰關聯的數組項(類似於數據庫選擇查詢)。所以如果我搜索'dummy',那麼它應該返回這個數組的第一個項目。在多維數組中搜索值並保持鍵的關聯
Array ( [12.12.2014] => Array ( [7] => Array ( [id] => 1672 [date] => 12.12.2014 [description] => rummy dummy data [room] => delux [Type] => garden [from] => 17:00 [to] => 17:45 [assets] => Array ( [asset] => Array ( [0] => Array ( [number] => 5275 [detail] => primary one ) [1] => Array ( [number] => 19 [detail] => secondary one ) ) ) [references] => Array ( [reference] => Array ( [personnumber] => 479470 [type] => worker [name] => David [department] => Sales [cv] => Array ( [pdetails] => follow later ) [profile] => True ) ) ) ) [13.12.2014] => Array ( [17] => Array ( [id] => 1672 [date] => 13.12.2014 [description] => brown fox jump [room] => star [Type] => city [from] => 17:00 [to] => 17:45 [assets] => Array ( [asset] => Array ( [number] => 5275 [detail] => prime two ) ) [references] => Array ( [reference] => Array ( [personnumber] => 479470 [type] => manager [name] => Albert [department] => Purchase [cv] => Array ( [pdetails] => follow later ) [profile] => True ) ) ) ) )
我試圖stripos搜索字符串中數組值和基於in_array功能,但是它要麼會產生不正確的結果或鍵關聯沒有被維持。
我無法找到維護鍵值的方法。
function search($array, $key, $value) { $results = array(); if (is_array($array)) { if (isset($array[$key]) && $array[$key] == $value) $results[] = $array; foreach ($array as $subarray) $results = array_merge($results, search($subarray, $key, $value)); } return $results; }
這可能是你見過的最糟糕的功能,但這可以完成這項工作。如果有人能夠遞歸(數組可能會更深)。
function search_in_multi_array($srchvalue, $array) { $foundkey = ''; if (is_array($array) && count($array) > 0) { foreach($array as $pkey => $pvalue) { foreach($pvalue as $ckey => $cvalue) { if (is_array($cvalue) && count($cvalue) > 0) { if(in_array($srchvalue,$cvalue)) { $foundkey[$pkey][$ckey] = $cvalue; } foreach($cvalue as $dkey => $dvalue) { if(!is_array($dvalue)) { $pos = stripos($dvalue, $srchvalue); if ($pos !== false) { $foundkey[$pkey][$ckey] = $cvalue; } } } } } } } return $foundkey; }
函數調用 - $針= '狐狸'; search_in_multi_array($ needle,$ my_array); 這是輸出
Array ( [13.12.2014] => Array ( [17] => Array ( [id] => 1672 [date] => 13.12.2014 [description] => brown fox jump [room] => star [Type1] => city [from] => 17:00 [to] => 17:45 [assets] => Array ( [asset] => Array ( [number] => 5275 [detail] => prime two ) ) [references] => Array ( [reference] => Array ( [personnumber] => 479470 [Type1] => manager [name] => Albert [department] => Purchase [cv] => Array ( [pdetails] => follow later ) [profile] => 1 ) ) ) ) )
你必須顯示你已經嘗試過 – hindmost 2014-08-29 09:52:57
給定數組的期望輸出是什麼。舉一些例子 – 2014-08-29 09:55:21
看看這裏:http://stackoverflow.com/questions/6661530/php-multi-dimensional-array-search – 2014-08-29 09:56:54