2013-09-10 155 views
1

我想我可以用一個foreach循環這樣做:PHP,檢查是否有屬性=值對象中的對象的數組存在

foreach ($haystack as $item) 
     if (isset($item->$needle_field) && $item->$needle_field == $needle) 
      return true; 
} 

但我是遊蕩,如果它可能沒有環辦?

類似:

if(in_array($item->$needle_field == $needle,$haystack) 
      return true; 

回答

1

這是可能的,但它沒有任何好轉:

<?php 
function make_subject($count, $success) { 
    $ret = array(); 
    for ($i = 0; $i < $count; $i++) { 
     $object = new stdClass(); 
     $object->foo = $success ? $i : null; 
     $ret[] = $object; 
    } 
    return $ret; 
} 

// Change true to false for failed test. 
$subject = make_subject(10, true); 

if (sizeof(array_filter($subject, function($value) { 
    return $value->foo === 3; 
}))) { 
    echo 'Value 3 was found!'; 
} else { 
    echo 'Value 3 was not found.'; 
} 

輸出Value 3 was found!

我勸你留在for循環:這是清晰,不像什麼招數拯救一條線,你可能會發現。

0
array_key_exists

可能:

if (array_key_exists($needle_field, $haystack) { 
    if ($haystack[$needle_field] == $needle) { 
    echo "$needle exists"; 
    } 
} 
相關問題