简体   繁体   中英

check associative array contains value

    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 
    )
) 

this is my multidimensional

Now i want to initially check array contains [required] => 1 or [required] => 0

i don't want to traversing array

Let's say your array name is $myarray

So you can do something like this -

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
    }
}
if($yourArr[0]['required']==0)  //Just check for first element in your array
  echo "Zero";
else
  echo "One";
foreach($mainarray as $array ){ //check for each 
  if($array['required']==1)
   //doSome Task
  if($array['required']==0)

This is probably the most hackish solution I'll come up with all this morning, but if you are shooting for a quick one-liner, this should do:

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

Edit: This assumes you've got PHP 5.5+ at hand

Update: After a closer look at the documentation of in_array() , this should be possible:

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

As an alternative, my way independent of the array structure (assume $x holds your data structure):

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM