我的多维数组是
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 db
但如果数组中存在[required] => 1
,我就不想提交任何值
所以,如何检查天气整个阵列conatins [required] => 1
答案 0 :(得分: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.
}
答案 1 :(得分: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';
}
答案 2 :(得分: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;
}