2011-09-20 74 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 
    } 
} 
相关问题