2017-08-10 238 views
0

搜索值的組合我有一個多維數組:PHP多維陣列中陣列

$array = 
    Array ( 
    [0] => Array ([id] => 2 [zoneId] => 2 [buildingId] => 2 [typeId] => 2) 
    [1] => Array ([id] => 4 [zoneId] => 2 [buildingId] => 2 [typeId] => 1) 
    [2] => Array ([id] => 6 [zoneId] => 6 [buildingId] => 17 [typeId] => 2)) 

而且我想如果組合進行搜索,例如,[buildingId] => 2,[TYPEID] => 2存在是陣列0,1或2。

我嘗試以下:

$keyType = array_search(2, array_column($array, 'typeId')); 
$keyBuilding = array_search(2, array_column($array, 'buildingId')); 

if(is_numeric($keyType)&&is_numeric($keyBuilding)){ 
    echo 'Combination does exists' 
} 

此工作,但也給出了假陽性,如果我將搜索[buildingId] => 17,[ typeId] => 1 ñ我解決這個問題?

編輯

我也想知道,如果組合不是在數組中,我該怎麼安排呢?

if($result == false){ 
echo 'does not exists'; 
} 

回答

0
$buildingId = 2; 
$typeId = 2; 
$result = false; 
foreach ($array as $key => $val) { 
    if ($val['buildingId'] == $buildingId && $val['typeId'] == $typeId) { 
     $result = $key; // If you want the key in the array 
     $result = $val; // If you want directly the entry you're looking for 
     break; // So that you don't iterate through the whole array while you already have your reuslt 
    } 
} 
+0

非常感謝你:D這個作品! –

+0

如果我想知道組合typeId = 17和buildingId = 1不存在,我該怎麼做? –

+0

@LoesVisser如果沒有找到rsult,'foreach'後面的'$ result'評估爲'false'。 – ksjohn

1

你可以試試這個代碼:

$keyTypeExistsAndHaveSameValue = isset($array['typeId']) && $array['typeId'] === 2; 
$keyBuildingExistsAndHaveSameValue = isset($array['buildingId']) && $array['buildingId'] === 2; 

if($keyTypeExistsAndHaveSameValue && $keyBuildingExistsAndHaveSameValue){ 
    echo 'Combination does exists' 
} 

此代碼檢查是否存在TYPEID & buildingId密鑰,但它也檢查其值是2和2

0

我想你需要的是這個

$keyType = array_search(1, array_column($array, 'typeId')); 
$keyBuilding = array_search(17, array_column($array, 'buildingId')); 

if(is_numeric($keyType)||is_numeric($keyBuilding)){ 
    echo 'Combination does exists'; 
} 

現在,您需要或運營商inste廣告和運營商,因爲您想要typeid = 1存在或建築id = 17存在。

如果我已經正確理解你的問題,那麼你正在嘗試做這樣的事情,對吧?

希望這會有所幫助!

0

你需要做一個foreach循環來獲得實際的數組編號,另一個解決方案似乎不能回答你要找的東西,那就是索引號。

我想如果組合進行搜索,例如,[buildingId] => 2,[TYPEID] => 2存在是陣列0,1或2。

編輯:這代碼只是示例代碼,以顯示你如何獲取數組索引號,在生產環境中,你將節省的匹配陣列,比較數字沒有硬編碼等...

$array = array(array('id' => 2, 'zoneId' => 2, 'buildingId' => 2, 'typeId' => 2), 
      array('id' => 4, 'zoneId' => 2, 'buildingId' => 2, 'typeId' => 2), 
      array('id' => 6, 'zoneId' => 6, 'buildingId' => 17, 'typeId' => 2)); 


foreach ($array as $building => $building_details) 
{ 
    if ($building_details['buildingId'] === 2 && $building_details['typeId'] === 2) 
    { 
     echo 'Array number ' . $building . ' matches criteria<br>'; 
    } 
} 

輸出:

Array number 0 matches criteria 
Array number 1 matches criteria 

您可以在線查看該片段here