检查关联数组包含值

时间:2014-09-23 06:26:47

标签: php

    Array (    
    [0] => Array ( 
               [questionID] => 47
               [surveyID] => 51
               [userID] => 31 
               [question_Title] => Choose Any One? 
               [question_Type] => Dropdown 
               [response] => 1.Android 2.Windows 3.Blackberry 
               [required] => 0 
               [add_time] => 0
    )
    [1] => Array ( 
               [questionID] => 48 
               [surveyID] => 51 
               [userID] => 31 
               [question_Title] => Is it? 
               [question_Type] => Bigbox 
               [response] => Yes No 
               [required] => 1 
               [add_time] => 0 
    )    
    [2] => Array ( 
               [questionID] => 129 
               [surveyID] => 51 
               [userID] => 31 
               [question_Title] => sELECT 
               [question_Type] => Single 
               [response] => DFG HBK GHCK HK 
               [required] => 0 
               [add_time] => 0 
    )
) 

这是我的多维

现在我想最初检查数组包含[required] => 1或[required] => 0

我不想遍历数组

5 个答案:

答案 0 :(得分:1)

我们假设您的数组名称为$myarray

所以你可以这样做 -

foreach($myarray as $arrelement)
{
    if(isset($arrelement[required]) && $arrelement[required] == 1) //choose 1 or 0 in code as per your need
    {
         //traverse your array and do needful
    }
}

答案 1 :(得分:1)

if($yourArr[0]['required']==0)  //Just check for first element in your array
  echo "Zero";
else
  echo "One";

答案 2 :(得分:0)

foreach($mainarray as $array ){ //check for each 
  if($array['required']==1)
   //doSome Task
  if($array['required']==0)

答案 3 :(得分:0)

这可能是我今天早上想出来的最狡猾的解决方案,但是如果你要快速拍摄单行,那应该这样做:

if(in_array(1, array_column($myArray, 'required')))
   echo 'required';

编辑:假设您手头有PHP 5.5+

更新:仔细查看in_array()的文档后,这应该是可能的:

if(in_array(array('required' => 1), $myArray))
    echo 'required';

答案 4 :(得分:0)

作为替代方案,我的方式独立于数组结构(假设$ x保存您的数据结构):

if (preg_match('/"required":[01]/',json_encode($x))) {
    // The array structure contains "required" => 0 or "required" => 1
} else {
    // Negative
}