2010-07-29 52 views
-1

有一个变量$list,它有一些数组。PHP check array

printr_r($list); 

给出类似:

Array (
    [0] => stdClass Object (
     [ID] => 1 
     [name] => Martha Dandridge 
    ) 
    [1] => stdClass Object (
     [ID] => 35 
     [name] => Abigail Smith 
    ) 
    [2] => stdClass Object (
     [ID] => 153 
     [name] => Julia Gardiner 
    ) 
    [3] => stdClass Object (
     [ID] => 271 
     [name] => Hillary Rodham 
    ) 
    [4] => stdClass Object (
     [ID] => 124 
     [name] => Nancy Davis 
    ) 
) 

我们应该检查,如果该阵列中的任何条目[name]一直希望值。

像:

if($list has "Nancy Davis" or "Hillary Rodham" in [name] of some entry?) { 
    return true; 
} else { 
    return false; 
} 

我们有“南希·戴维斯”和“希拉里”我们的阵中,所以它应该给true

如果我们问这样的:

if($list has "George Bush" or "Lou Henry" or "Helen Herron" in [name] of some entry?) { ... } 

它应该给false,因为没有任何name这样的值。

阵列中可以有任意数量的条目(我的意思是[0], [1] ... [any]),它应该检查每个条目的[name]

+0

那你试试这么远? – relet 2010-07-29 14:55:37

+0

这是功课吗?回复:*请为此提供工作代码*:这不是如何工作(实际上它被认为是粗鲁的要求代码)。请显示你到目前为止。 – 2010-07-29 14:55:38

+0

您可能对本网站的工作原理有错误的印象。我们可以*协助您,但我们需要您的帮助。你不能指望我们给你的代码没有你让你的手有点肮脏。如果有的话,这将有助于发布你尝试过的东西。 – 2010-07-29 14:56:33

回答

0
$match = false; 
foreach($list as $value){ 
    if($value->name == "George Bush" || $value->name =="Lou Henry" || $value->name == "Helen Herron") { 
    $match = true; 
    break; 
    } 
} 

if($match) { 
    // do some if true 
} else { 
    // do dome if false 
} 
+0

使用“或”可以吗?不适合我。 – James 2010-07-29 15:18:16

+0

你能提供你在使用我的代码时想要做什么吗? – antyrat 2010-07-29 15:21:28

+2

'或'在Python中有效,但不在PHP中。即使你用'||'替换'或'也不行。 'if'陈述是错误的。 – 2010-07-29 15:30:42

0

您应该尝试使用php in_array函数。

if (in_array('Martha Dandridge', $list) || in_array('Abigail Smith', $list)) { 
    # do something based on the fact that the elements are in the array $list 
} else { 
    # do something else based on the fact the the elements do no exist in the array $list 
} 
+0

不明白 – James 2010-07-29 15:06:18

+0

我刚编辑我的代码片段,这应该会帮助你理解。 – Martin 2010-07-29 15:25:50

+0

它应该是[name]值 – James 2010-07-29 15:36:58

0

你也可以去

if ($arr['Janice'] !== null || $arr['Bill'] !== null) { 
... 
}