2011-09-20 45 views
2

我試圖檢查一個id是否在std對象數組內可用,我不想通過數組來循環它將不會顯示正確的信息。我的代碼如下:我如何檢查數組值是否在stdclass對象數組內可用

Array(
    [0] => stdClass Object 
     (
      [name] => My Name 
      [id] => 1234567890 
     ) 
    [1] => stdClass Object 
     (
      [name] => Other User Name 
      [id] => 987654321 
     ) 
) 

我嘗試使用in_array方法和它沒有找到ID鍵和值。

謝謝 d ~~

+0

循環出了什麼問題?爲什麼不循環會給你正確的數據? –

+0

您將以某種方式必須遍歷數組才能通過id值查找條目。也許你可以解釋「......因爲它不會顯示正確的信息」更好一點。 – Yoshi

+0

你是什麼意思,你不想通過數組循環?據我可以告訴它將是你唯一的解決方案 – thomaux

回答

2

你需要循環的陣列到陣列中的對象的屬性進行檢查。編寫將返回像(僞代碼)所需值的函數:

function returnObjectForId($idToMatch){ 
    foreach ($array as $i => $object) { 
     if($object->id == $idToMatch){ 
      return $object 
     } 
    } 
} 
+0

謝謝,自從我編寫了PHP以來,已經有一段時間了:) – thomaux

0

隨着Anzeo的答案的幫助下,我升級這一點與其他性質的工作,並在條件語句中使用,採取偷看:

function my_in_array($needle, $haystack = array(), $property){ 
    foreach ($haystack as $object) { 
     if($object->$property == $needle){ 
      return true; 
     } else { 
      return false; 
     } 
    } 
} 
foreach($foo as $bar) { 
    if(!my_in_array($bar, $arrWithObjects, 'id')) { 
     //do something 
    } 
} 

希望這是別人

編輯

有用我也發現了一個很不錯的技巧,以對象的屬性轉換爲數組,這可能在某些情況下幫助。

foreach($arrWithObjects as $obj) { 
    $objProps = get_object_vars($obj); 
    if(in_array('My Name', $objProps)) { 
     //do something 
    } 
} 
相關問題