2014-09-23 85 views
0

我多維數組檢查數組多維數組包含值或不

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 
      )  

     ) 

然後使用foreach循環我提交的每個值,將其插入MySQL數據庫 但如果數組存在[required] => 1我不想提交的任何值

所以,如何檢查天氣整個陣列conatins [需要] => 1

+1

你嘗試過這麼遠嗎?你是否搜索了這個問題?請參閱http://stackoverflow.com/questions/6661530/php-multi-dimensional-array-search?lq=1 – 2014-09-23 10:50:45

+0

謝謝@i驚慌的外星人 – 2014-09-23 10:52:20

+0

[檢查聯合數組包含值](http:// stackoverflow。 com/questions/25988258/check-associative-array-contains-value) – DaSourcerer 2014-09-25 07:22:56

回答

0

似乎簡單的足夠foreach循環就可以了:

foreach($mainArray as $miniArray) 
{ 
    if($miniArray['required']==1) 
    { 
     // Do insert stuff here. 
    } 
} 

或者,如果你想檢查是否你進入它之前的任何地方存在於數組中,一個簡單的布爾應該做的伎倆:

$hasRequired=false; 
foreach($mainArray as $miniArray) 
{ 
    if($miniArray['required']==1) 
    { 
     $hasRequired=true; 
    } 
} 

if($hasRequired) 
{ 
    // Do Insert Stuff here. 
} 
+0

thanx @ Fluffehbut,但我的問題是使用foreach循環的 – 2014-09-23 10:56:46

+0

我提交每個值並將其插入到MySQL數據庫中,但如果數組中存在[required] => 1我不想提交任何值? – 2014-09-23 10:57:30

+0

使用'array_filter'或2'foreach' – 2014-09-23 10:58:14

0

您可以使用array_filter:

$test_array = array(
    array(
     "required"=>0, 
     "other_field"=>"value" 
    ), 
    array(
     "required"=>0, 
     "other_field"=>"value" 
    ), 
    array(
     "required"=>0, 
     "other_field"=>"value" 
    ), 
); 

function checkIfRequired($var) 
{ 
    return (is_array($var) && $var['required'] == 1); 
} 

if(sizeof(array_filter($test_array, "checkIfRequired"))){ 
    print 'required field exists'; 
} 
else{ 
    print 'required field does not exist'; 
} 
0

您可以使用is_array或in_array函數來檢查數組的值。但is_array函數比in_array更快更準確。 這裏是一個來自PHP手冊的例子。這個函數將檢查整個數組。

function myInArray($array, $value, $key){ 
//loop through the array 
foreach ($array as $val) { 
    //if $val is an array cal myInArray again with $val as array input 
    if(is_array($val)){ 
    if(myInArray($val,$value,$key)) 
     return true; 
    } 
    //else check if the given key has $value as value 
    else{ 
    if($array[$key]==$value) 
     return true; 
    } 
} 
return false; 

}