2015-03-24 75 views
0

我已經能夠在查詢後創建數組。檢查數組中的值,並創建php語句

<? 
    $results = array(); 
    while($row = mysql_fetch_assoc($result)) 
    { 
     $results[] = $row; 
    } 
?> 

我現在已經從查詢結果如下數組:

array(2) { 
    [0]=> 
    array(1) { 
    ["form_type"]=> 
    string(6) "VF-302" 
    } 
    [1]=> 
    array(1) { 
    ["form_type"]=> 
    string(6) "VF-301" 
    } 
} 

如果,例如, 「VF-301」 值存在數組,你會一個PHP if語句是什麼?

<? //not working 
    if(in_array("VF-300", $results)){ 
    echo "this value is in array"; 
    } else { 
    echo "this value is not in array"; 
    } 
    ?> 
+1

[in \ _array()and multidimensional array](http://stackoverflow.com/questions/4128323/in-array-and-multidimensional-array) – kero 2015-03-24 21:40:41

+0

如果您不需要其他行,你應該在查詢中這樣做。 – 2015-03-24 21:47:35

回答

1
foreach($results as $result) { 
    if(in_array("VF-300", $result)){ 
     echo "this value is in array"; 
    } else { 
     echo "this value is not in array"; 
    } 
} 

需要考慮到嵌套數組

0

您在包含其他數組的數組中搜索值爲VF-300

您需要循環所有值。如果您知道在從數據庫填充數組時需要執行的操作,則可以使用該循環。

while($row = mysql_fetch_assoc($result)) 
    { 
     if(in_array("VF-300", $row)){ 
      echo "this value is in array"; 
     } else { 
      echo "this value is not in array"; 
     } 
     $results[] = $row; 

另外,您將需要再次循環。

0

在這裏,我覺得做什麼。這是有效的,因爲你的原始數組是由其他數組構成的,所以如果你只是使用in_array,它會檢查成員中的值而不是值。這個功能對你來說是這樣的:

function in_array_m($needle,$haystack) { 
     return in_array(true,array_map(function($v) use($needle,$haystack) { 
      return in_array($needle,$v); 
     },$haystack)); 
    } 

典型的解決方案涉及一個循環,但我想弄得一團糟!

此解決方案優於其他人的優勢在於,您只能得到真或假,而不是每個子集的結果!