如何检查数组是否只包含PHP中的其他数组?
I'm looking for a simple way/function to tell me if an array contains only other arrays or if there are values contained as well. For example,
$a = array(array(), array(), array())
should end up with a 'true' result but
$b = array(array(), 1, 17)
should end up with a 'false result.
I know I can do the following,
function isArrayOfArrays($a) {
foreach ($a as $value) {
if (!is_array($value))
return false;
}
return true;
}
I'm wondering if there is a more elegant way.
我正在寻找一种简单的方法/函数来告诉我数组是否只包含其他数组或是否有 包含的价值。 例如, p>
$ a = array(array(),array(),array())
code> pre>
应该以'true'结果但 p>
$ b = array(array(),1,17)
code> pre>
应该以“错误结果”结束。 p>
我知道我可以执行以下操作, p>
function isArrayOfArrays( $ a){
foreach($ a as $ value){
if(!is_array($ value))
return false;
}
返回true;
}
code> pre>
我想知道是否有更优雅的方式。 p>
div>
You can try with array_filter
:
$isArrayOfArrays = empty( array_filter($b, function($item){
return !is_array($item);
}) );
Or even shorter:
$isArrayOfArrays = array_filter($b, 'is_array') === $b;
I'm fond of higher-order functions and the map-reduce paradigm:
/**
* && as a function.
*
* This is our reducer.
*/
function andf($a, $b)
{
return $a && $b;
}
function isArrayOfArrays($a)
{
if (!is_array($a)) {
return false;
}
return array_reduce(array_map('is_array', $a), 'andf', true);
}
This has slightly different semantics from your version, but I argue they are more correct (if it's not an array in the first place, it can hardly be an array of arrays can it?).
This formulation is arguably more elegant, but the difference is so small I would probably use the loop in actual code.