check associative array contains value

后端 未结 5 1668
粉色の甜心
粉色の甜心 2021-01-26 01:27
    Array (    
    [0] => Array ( 
               [questionID] => 47
               [surveyID] => 51
               [userID] => 31 
               [question         


        
相关标签:
5条回答
  • 2021-01-26 02:14
    foreach($mainarray as $array ){ //check for each 
      if($array['required']==1)
       //doSome Task
      if($array['required']==0)
    
    0 讨论(0)
  • 2021-01-26 02:18

    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';
    
    0 讨论(0)
  • 2021-01-26 02:23
    if($yourArr[0]['required']==0)  //Just check for first element in your array
      echo "Zero";
    else
      echo "One";
    
    0 讨论(0)
  • 2021-01-26 02:25

    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
    }
    
    0 讨论(0)
  • 2021-01-26 02:27

    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
        }
    }
    
    0 讨论(0)
提交回复
热议问题