2010-07-29 54 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) { 
... 
}