2015-03-24 74 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)); 
    } 

典型的解决方案涉及一个循环,但我想弄得一团糟!

此解决方案优于其他人的优势在于,您只能得到真或假,而不是每个子集的结果!