如何检查数组是否包含PHP中的另一个数组?
问题描述:
I would have a rather simple question today. We have the following resource:
$a = array(1 => 5, 2 => 3, 3 => 13, 9 => array('test'), 4 => 32, 5 => 33);
How is it actually possible to find out if array "a" has an array element in it and return the key if there is one (or more)?
今天我会有一个相当简单的问题。 我们有以下资源: p>
$ a = array(1 => 5,2 => 3 = 3 => 13,9 => array(' test'),4 => 32,5 => 33);
code> pre>
如何确定数组“a”是否有数组? 其中的元素,如果有一个(或更多),则返回密钥? p>
div>
答
One possible approach:
function look_for_array(array $test_var) {
foreach ($test_var as $key => $el) {
if (is_array($el)) {
return $key;
}
}
return null;
}
It's rather trivial to convert this function into collecting all such keys:
function look_for_all_arrays(array $test_var) {
$keys = [];
foreach ($test_var as $key => $el) {
if (is_array($el)) {
$keys[] = $key;
}
}
return $keys;
}
Demo.
答
You can use foreach since you are looking for any array:
foreach ($a as $key => $test) {
if (is_array($test)) {
$keys[] = $key;
}
}
All keys of arrays for the array $a
will be in the array $keys
.
答
$array = array(1 => 5, 2 => 3, 3 => 13, 9 => array('test'), 4 => 32, 5 => 33);
foreach($array as $key => $value){
if(is_Array($value)){
echo $value[key($value)];
}
}
答
I have tried in different way.
$a = array(1 => 5, 2 => 3, 3 => 13, 9 => array('test'), 4 => 32, 5 => 33);
foreach ( $a as $aas ):
if(is_array($aas)){
foreach ($aas as $key => $value):
echo " (child array is this $key : $value)";
endforeach;
}else{
echo " Value of array a = $aas : ";
}
endforeach;
output is like :
Value of array a = 5 : Value of array a = 3 :
Value of array a = 13 : (child array is this 0 :
test) Value of array a = 32 : Value of array a = 33 :