如何检查多维数组只包含php中的int值
有没有最简单的检查。
就像我有一个包含int值的数组但我必须检查所有值是否在
数组1
$RoomGuests = array(
array(
"NoOfAdults"=> 2,
"NoOfChild"=>0,
),
array(
"NoOfAdults"=> 3,
"NoOfChild"=>2,
"ChildAge"=> array(12,11)
),
array(
"NoOfAdults"=> 3,
"NoOfChild"=>1,
"ChildAge"=> array(11)
)
);
上面的数组只包含int值,那么它是 true
ARRAY2
$RoomGuests2 = array(
array(
"NoOfAdults"=> "two",
"NoOfChild"=>0,
),
array(
"NoOfAdults"=> "three",
"NoOfChild"=>"two",
"ChildAge"=> array(12,11)
),
array(
"NoOfAdults"=> 3,
"NoOfChild"=>1,
"ChildAge"=> array(11)
)
);
上面的数组不包含int值,那么它是 false
ARRAY3
$RoomGuests3 = array(
array(
"NoOfAdults"=> 2,
"NoOfChild"=>0,
),
array(
"NoOfAdults"=> 3,
"NoOfChild"=>2,
"ChildAge"=> array(12,11)
),
array(
"NoOfAdults"=> 3,
"NoOfChild"=>1,
"ChildAge"=> array(
"NoOfAdults"=> 3,
"NoOfChild"=>1,
"ChildAge"=> array(11,'k')
)
)
);
答案 0 :(得分:2)
您可以使用foreach()
循环父数组和array_walk_recursive()
函数来检查子项。
像这样:
$RoomGuests2 = array(
array(
"NoOfAdults"=> "two",
"NoOfChild"=>0,
),
array(
"NoOfAdults"=> "three",
"NoOfChild"=>"two",
"ChildAge"=> array(12,11)
),
array(
"NoOfAdults"=> 3,
"NoOfChild"=>1,
"ChildAge"=> array(11)
)
);
foreach($RoomGuest2 as $child) {
array_walk_recursive($child, 'checkIfInt');
}
function checkIfInt($array, $key) {
// If the child array is another array (like "ChildAge"=> array(11)) then check this array.
if(is_array($array[$key])) array_walk_recursive($array[$key], 'checkIfInt');
else if(!is_integer($array[$key])) {
// If the value it's not a integer, then PHP will execute this code.
}
}
答案 1 :(得分:2)
它可能对你有帮助
var_dump(is_IntArray($RoomGuests));
var_dump(is_IntArray($RoomGuests2));
var_dump(is_IntArray($RoomGuests3));
function is_IntArray($p){
$Result = is_array($p) ?
implode('', array_map(__FUNCTION__, array_fill(0, count($p), ''), $p)) :
$p;
return ctype_digit($Result);
}
答案 2 :(得分:0)
为什么不呢:
function containsOnlyIntegers($array) {
foreach($array as $arr) {
foreach($arr as $k => $a) {
if ($k === 'NoOfAdults' || $k === 'NoOfChild') {
if (!is_int($a)) { return false; }
}
}
}
return true;
}