- What is the most efficient way to check if an array is a flat array of primitive values or if it is a multidimensional array?
- 检查数组是原始值的平面数组还是多维数组,最有效的方法是什么?
- Is there any way to do this without actually looping through an array and running
is_array()
on each of its elements? - 是否有一种方法可以做到这一点,而不需要对数组进行循环,并且在每个元素上运行is_array() ?
21 个解决方案
#1
115
The short answer is no you can't do it without at least looping implicitly if the 'second dimension' could be anywhere. If it has to be in the first item, you'd just do
简而言之,如果“第二个维度”在任何地方都可能存在,那么你至少要隐式循环才能做到这一点。如果它必须出现在第一项中,你就会去做
is_array($arr[0]);
But, the most efficient general way I could find is to use a foreach loop on the array, shortcircuiting whenever a hit is found (at least the implicit loop is better than the straight for()):
但是,我能找到的最有效的通用方法是在数组上使用foreach循环,每当发现命中时都进行短路(至少隐式循环比for()更好):
$ more multi.php
<?php
$a = array(1 => 'a',2 => 'b',3 => array(1,2,3));
$b = array(1 => 'a',2 => 'b');
$c = array(1 => 'a',2 => 'b','foo' => array(1,array(2)));
function is_multi($a) {
$rv = array_filter($a,'is_array');
if(count($rv)>0) return true;
return false;
}
function is_multi2($a) {
foreach ($a as $v) {
if (is_array($v)) return true;
}
return false;
}
function is_multi3($a) {
$c = count($a);
for ($i=0;$i<$c;$i++) {
if (is_array($a[$i])) return true;
}
return false;
}
$iters = 500000;
$time = microtime(true);
for ($i = 0; $i < $iters; $i++) {
is_multi($a);
is_multi($b);
is_multi($c);
}
$end = microtime(true);
echo "is_multi took ".($end-$time)." seconds in $iters times\n";
$time = microtime(true);
for ($i = 0; $i < $iters; $i++) {
is_multi2($a);
is_multi2($b);
is_multi2($c);
}
$end = microtime(true);
echo "is_multi2 took ".($end-$time)." seconds in $iters times\n";
$time = microtime(true);
for ($i = 0; $i < $iters; $i++) {
is_multi3($a);
is_multi3($b);
is_multi3($c);
}
$end = microtime(true);
echo "is_multi3 took ".($end-$time)." seconds in $iters times\n";
?>
$ php multi.php
is_multi took 7.53565130424 seconds in 500000 times
is_multi2 took 4.56964588165 seconds in 500000 times
is_multi3 took 9.01706600189 seconds in 500000 times
Implicit looping, but we can't shortcircuit as soon as a match is found...
隐式循环,但是一旦找到匹配,我们就不能短路……
$ more multi.php
<?php
$a = array(1 => 'a',2 => 'b',3 => array(1,2,3));
$b = array(1 => 'a',2 => 'b');
function is_multi($a) {
$rv = array_filter($a,'is_array');
if(count($rv)>0) return true;
return false;
}
var_dump(is_multi($a));
var_dump(is_multi($b));
?>
$ php multi.php
bool(true)
bool(false)
#2
170
Use count() twice; one time in default mode and one time in recursive mode. If the values match, the array is not multidimensional, as a multidimensional array would have a higher recursive count.
使用count()两次;一次在默认模式下,一次在递归模式下。如果值匹配,则数组不是多维的,因为多维数组具有更高的递归计数。
if (count($array) == count($array, COUNT_RECURSIVE))
{
echo 'array is not multidimensional';
}
else
{
echo 'array is multidimensional';
}
This option second value mode
was added in PHP 4.2.0. From the PHP Docs:
在PHP 4.2.0中添加了此选项的第二个值模式。从PHP文档:
If the optional mode parameter is set to COUNT_RECURSIVE (or 1), count() will recursively count the array. This is particularly useful for counting all the elements of a multidimensional array. count() does not detect infinite recursion.
如果可选模式参数设置为count_recursive(或1),则count()将递归地计数数组。这对于计算多维数组的所有元素特别有用。count()不检测无限递归。
However this method does not detect array(array())
.
但是,此方法不检测数组(array()))。
#3
27
For PHP 4.2.0 or newer:
对于PHP 4.2.0或更新版本:
function is_multi($array) {
return (count($array) != count($array, 1));
}
#4
9
You can simply execute this:
你可以简单地执行以下操作:
if (count($myarray) !== count($myarray, COUNT_RECURSIVE)) return true;
else return false;
If the optional mode parameter is set to COUNT_RECURSIVE
(or 1), count() will recursively count the array. This is particularly useful for counting all the elements of a multidimensional array.
如果可选模式参数设置为count_recursive(或1),则count()将递归地计数数组。这对于计算多维数组的所有元素特别有用。
If it's the same, means there are no sublevels anywhere. Easy and fast!
如果它是相同的,意味着任何地方都没有子级别。容易和快速!
#5
7
You could look check is_array()
on the first element, under the assumption that if the first element of an array is an array, then the rest of them are too.
您可以在第一个元素上检查is_array(),假设如果数组的第一个元素是数组,那么其他元素也是。
#6
7
I think this is the most straight forward way and it's state-of-the-art:
我认为这是最直接的方式,它是最先进的:
function is_multidimensional(array $array) {
return count($array) !== count($array, COUNT_RECURSIVE);
}
#7
4
All great answers... here's my three lines that I'm always using
所有伟大的答案……这是我常用的三行
function isMultiArray($a){
foreach($a as $v) if(is_array($v)) return TRUE;
return FALSE;
}
#8
2
This function will return int number of array dimensions (stolen from here).
这个函数将返回数组维度的int数(从这里偷来)。
function countdim($array)
{
if (is_array(reset($array)))
$return = countdim(reset($array)) + 1;
else
$return = 1;
return $return;
}
#9
2
I think you will find that this function is the simplest, most efficient, and fastest way.
我想你会发现这个函数是最简单,最有效,最快捷的方法。
function isMultiArray($a){
foreach($a as $v) if(is_array($v)) return TRUE;
return FALSE;
}
You can test it like this:
你可以这样测试它:
$a = array(1 => 'a',2 => 'b',3 => array(1,2,3));
$b = array(1 => 'a',2 => 'b');
echo isMultiArray($a) ? 'is multi':'is not multi';
echo '<br />';
echo isMultiArray($b) ? 'is multi':'is not multi';
#10
1
You can also do a simple check like this:
你也可以做一个简单的检查:
$array = array('yo'=>'dream', 'mydear'=> array('anotherYo'=>'dream'));
$array1 = array('yo'=>'dream', 'mydear'=> 'not_array');
function is_multi_dimensional($array){
$flag = 0;
while(list($k,$value)=each($array)){
if(is_array($value))
$flag = 1;
}
return $flag;
}
echo is_multi_dimensional($array); // returns 1
echo is_multi_dimensional($array1); // returns 0
#11
1
Try as follows
尝试如下
if (count($arrayList) != count($arrayList, COUNT_RECURSIVE))
{
echo 'arrayList is multidimensional';
}else{
echo 'arrayList is no multidimensional';
}
#12
0
I think this one is classy (props to another user I don't know his username):
我觉得这个很不错(我不知道他的用户名):
static public function isMulti($array)
{
$result = array_unique(array_map("gettype",$array));
return count($result) == 1 && array_shift($result) == "array";
}
#13
0
All the above methods are too complex for quick rolling out. If an array is flat, testing the first element should return a primitive e.g int, string e.t.c. If it is multidimensional, it should return an array. By extension, you can use this one liner fast and neat.
以上所有方法都过于复杂,难以快速推出。如果数组是平的,那么测试第一个元素应该返回一个原语e。如果它是多维的,它应该返回一个数组。通过扩展,您可以快速和整洁地使用这一行。
echo is_array(array_shift($myArray));
if this returns true, the array is multidimensional. Else it is flat. Just to note, it is very rare for arrays to have different dimensions e.g. if you are generating data from a model, it will always have the same type of multidimensional or flat structure that can be traversed by loops. If it isn't, then you have custom built it by hand, which means you know where everything will be and it just works without needing to write a looping algorithm
如果返回true,则该数组是多维的。否则它是平的。要注意的是,数组具有不同的维度是非常罕见的,例如,如果您从一个模型中生成数据,那么它总是具有相同类型的多维或扁平结构,可以通过循环遍历。如果它不是,那么您就可以手工构建它,这意味着您知道所有的东西都在哪里,并且不需要编写循环算法就可以工作
#14
0
In addition to the previous answers and depending on the schema of the array you want to check:
除了前面的答案,根据数组的模式,您还需要检查:
function is_multi_array($array=[],$mode='every_key'){
$result = false;
if(is_array($array)){
if($mode=='first_key_only'){
if(is_array(array_shift($array))){
$result = true;
}
}
elseif($mode=='every_key'){
$result = true;
foreach($array as $key => $value){
if(!is_array($value)){
$result = false;
break;
}
}
}
elseif($mode=='at_least_one_key'){
if(count($array)!==count($array, COUNT_RECURSIVE)){
$result = true;
}
}
}
return $result;
}
#15
0
Even this works
即使这工作
is_array(current($array));
If false its a single dimension array if true its a multi dimension array.
如果为假,它是一个一维数组,如果为真,它是一个多维数组。
current will give you the first element of your array and check if the first element is an array or not by is_array function.
current将给出数组的第一个元素,并检查第一个元素是否是一个数组,而不是is_array函数。
#16
0
Don't use COUNT_RECURSIVE
不要使用COUNT_RECURSIVE
点击这个网站了解原因
use rsort and then use isset
使用rsort然后使用isset
function is_multi_array( $arr ) {
rsort( $arr );
return isset( $arr[0] ) && is_array( $arr[0] );
}
//Usage
var_dump( is_multi_array( $some_array ) );
#17
0
In my case. I stuck in vary strange condition.
1st case = array("data"=> "name");
2nd case = array("data"=> array("name"=>"username","fname"=>"fname"));
But if data
has array instead of value then sizeof() or count() function not work for this condition. Then i create custom function to check.
If first index of array have value then it return "only value"
But if index have array instead of value then it return "has array"
I use this way
在我的例子中。我陷入了各种奇怪的状况。第一种情况=数组(“data”=>“name”);2例=阵列(“数据”= >数组(“名字”= >“用户名”、“帧”= >“帧”));但是如果数据具有数组而不是值,那么sizeof()或count()函数在这种情况下不起作用。然后我创建自定义函数来检查。如果数组的第一个索引有值那么它返回的是"only value"但是如果索引有数组而不是value那么它返回的是"has array"我用这种方式
function is_multi($a) {
foreach ($a as $v) {
if (is_array($v))
{
return "has array";
break;
}
break;
}
return 'only value';
}
Special thanks to Vinko Vrsalovic
特别感谢Vinko Vrsalovic
#18
-1
if($array[0]){
//enter your code
}
#19
-1
if ( array_key_exists(0,$array) ) {
// multidimensional array
} else {
// not a multidimensional array
}
*only to those arrays with numeric index
*只对具有数值索引的数组
#20
-2
function isMultiArray(array $value)
{
return is_array(reset($value));
}
#21
-3
is_array($arr[key($arr)]);
No loops, plain and simple.
没有循环,简单明了。
Works also with associate arrays not only numeric arrays, which could not contain 0 ( like in the previous example would throw you a warning if the array doesn't have a 0. )
还可以使用关联数组,而不仅仅是不能包含0的数值数组(如前面的示例所示,如果数组没有0,那么将向您抛出一个警告)。
#1
115
The short answer is no you can't do it without at least looping implicitly if the 'second dimension' could be anywhere. If it has to be in the first item, you'd just do
简而言之,如果“第二个维度”在任何地方都可能存在,那么你至少要隐式循环才能做到这一点。如果它必须出现在第一项中,你就会去做
is_array($arr[0]);
But, the most efficient general way I could find is to use a foreach loop on the array, shortcircuiting whenever a hit is found (at least the implicit loop is better than the straight for()):
但是,我能找到的最有效的通用方法是在数组上使用foreach循环,每当发现命中时都进行短路(至少隐式循环比for()更好):
$ more multi.php
<?php
$a = array(1 => 'a',2 => 'b',3 => array(1,2,3));
$b = array(1 => 'a',2 => 'b');
$c = array(1 => 'a',2 => 'b','foo' => array(1,array(2)));
function is_multi($a) {
$rv = array_filter($a,'is_array');
if(count($rv)>0) return true;
return false;
}
function is_multi2($a) {
foreach ($a as $v) {
if (is_array($v)) return true;
}
return false;
}
function is_multi3($a) {
$c = count($a);
for ($i=0;$i<$c;$i++) {
if (is_array($a[$i])) return true;
}
return false;
}
$iters = 500000;
$time = microtime(true);
for ($i = 0; $i < $iters; $i++) {
is_multi($a);
is_multi($b);
is_multi($c);
}
$end = microtime(true);
echo "is_multi took ".($end-$time)." seconds in $iters times\n";
$time = microtime(true);
for ($i = 0; $i < $iters; $i++) {
is_multi2($a);
is_multi2($b);
is_multi2($c);
}
$end = microtime(true);
echo "is_multi2 took ".($end-$time)." seconds in $iters times\n";
$time = microtime(true);
for ($i = 0; $i < $iters; $i++) {
is_multi3($a);
is_multi3($b);
is_multi3($c);
}
$end = microtime(true);
echo "is_multi3 took ".($end-$time)." seconds in $iters times\n";
?>
$ php multi.php
is_multi took 7.53565130424 seconds in 500000 times
is_multi2 took 4.56964588165 seconds in 500000 times
is_multi3 took 9.01706600189 seconds in 500000 times
Implicit looping, but we can't shortcircuit as soon as a match is found...
隐式循环,但是一旦找到匹配,我们就不能短路……
$ more multi.php
<?php
$a = array(1 => 'a',2 => 'b',3 => array(1,2,3));
$b = array(1 => 'a',2 => 'b');
function is_multi($a) {
$rv = array_filter($a,'is_array');
if(count($rv)>0) return true;
return false;
}
var_dump(is_multi($a));
var_dump(is_multi($b));
?>
$ php multi.php
bool(true)
bool(false)
#2
170
Use count() twice; one time in default mode and one time in recursive mode. If the values match, the array is not multidimensional, as a multidimensional array would have a higher recursive count.
使用count()两次;一次在默认模式下,一次在递归模式下。如果值匹配,则数组不是多维的,因为多维数组具有更高的递归计数。
if (count($array) == count($array, COUNT_RECURSIVE))
{
echo 'array is not multidimensional';
}
else
{
echo 'array is multidimensional';
}
This option second value mode
was added in PHP 4.2.0. From the PHP Docs:
在PHP 4.2.0中添加了此选项的第二个值模式。从PHP文档:
If the optional mode parameter is set to COUNT_RECURSIVE (or 1), count() will recursively count the array. This is particularly useful for counting all the elements of a multidimensional array. count() does not detect infinite recursion.
如果可选模式参数设置为count_recursive(或1),则count()将递归地计数数组。这对于计算多维数组的所有元素特别有用。count()不检测无限递归。
However this method does not detect array(array())
.
但是,此方法不检测数组(array()))。
#3
27
For PHP 4.2.0 or newer:
对于PHP 4.2.0或更新版本:
function is_multi($array) {
return (count($array) != count($array, 1));
}
#4
9
You can simply execute this:
你可以简单地执行以下操作:
if (count($myarray) !== count($myarray, COUNT_RECURSIVE)) return true;
else return false;
If the optional mode parameter is set to COUNT_RECURSIVE
(or 1), count() will recursively count the array. This is particularly useful for counting all the elements of a multidimensional array.
如果可选模式参数设置为count_recursive(或1),则count()将递归地计数数组。这对于计算多维数组的所有元素特别有用。
If it's the same, means there are no sublevels anywhere. Easy and fast!
如果它是相同的,意味着任何地方都没有子级别。容易和快速!
#5
7
You could look check is_array()
on the first element, under the assumption that if the first element of an array is an array, then the rest of them are too.
您可以在第一个元素上检查is_array(),假设如果数组的第一个元素是数组,那么其他元素也是。
#6
7
I think this is the most straight forward way and it's state-of-the-art:
我认为这是最直接的方式,它是最先进的:
function is_multidimensional(array $array) {
return count($array) !== count($array, COUNT_RECURSIVE);
}
#7
4
All great answers... here's my three lines that I'm always using
所有伟大的答案……这是我常用的三行
function isMultiArray($a){
foreach($a as $v) if(is_array($v)) return TRUE;
return FALSE;
}
#8
2
This function will return int number of array dimensions (stolen from here).
这个函数将返回数组维度的int数(从这里偷来)。
function countdim($array)
{
if (is_array(reset($array)))
$return = countdim(reset($array)) + 1;
else
$return = 1;
return $return;
}
#9
2
I think you will find that this function is the simplest, most efficient, and fastest way.
我想你会发现这个函数是最简单,最有效,最快捷的方法。
function isMultiArray($a){
foreach($a as $v) if(is_array($v)) return TRUE;
return FALSE;
}
You can test it like this:
你可以这样测试它:
$a = array(1 => 'a',2 => 'b',3 => array(1,2,3));
$b = array(1 => 'a',2 => 'b');
echo isMultiArray($a) ? 'is multi':'is not multi';
echo '<br />';
echo isMultiArray($b) ? 'is multi':'is not multi';
#10
1
You can also do a simple check like this:
你也可以做一个简单的检查:
$array = array('yo'=>'dream', 'mydear'=> array('anotherYo'=>'dream'));
$array1 = array('yo'=>'dream', 'mydear'=> 'not_array');
function is_multi_dimensional($array){
$flag = 0;
while(list($k,$value)=each($array)){
if(is_array($value))
$flag = 1;
}
return $flag;
}
echo is_multi_dimensional($array); // returns 1
echo is_multi_dimensional($array1); // returns 0
#11
1
Try as follows
尝试如下
if (count($arrayList) != count($arrayList, COUNT_RECURSIVE))
{
echo 'arrayList is multidimensional';
}else{
echo 'arrayList is no multidimensional';
}
#12
0
I think this one is classy (props to another user I don't know his username):
我觉得这个很不错(我不知道他的用户名):
static public function isMulti($array)
{
$result = array_unique(array_map("gettype",$array));
return count($result) == 1 && array_shift($result) == "array";
}
#13
0
All the above methods are too complex for quick rolling out. If an array is flat, testing the first element should return a primitive e.g int, string e.t.c. If it is multidimensional, it should return an array. By extension, you can use this one liner fast and neat.
以上所有方法都过于复杂,难以快速推出。如果数组是平的,那么测试第一个元素应该返回一个原语e。如果它是多维的,它应该返回一个数组。通过扩展,您可以快速和整洁地使用这一行。
echo is_array(array_shift($myArray));
if this returns true, the array is multidimensional. Else it is flat. Just to note, it is very rare for arrays to have different dimensions e.g. if you are generating data from a model, it will always have the same type of multidimensional or flat structure that can be traversed by loops. If it isn't, then you have custom built it by hand, which means you know where everything will be and it just works without needing to write a looping algorithm
如果返回true,则该数组是多维的。否则它是平的。要注意的是,数组具有不同的维度是非常罕见的,例如,如果您从一个模型中生成数据,那么它总是具有相同类型的多维或扁平结构,可以通过循环遍历。如果它不是,那么您就可以手工构建它,这意味着您知道所有的东西都在哪里,并且不需要编写循环算法就可以工作
#14
0
In addition to the previous answers and depending on the schema of the array you want to check:
除了前面的答案,根据数组的模式,您还需要检查:
function is_multi_array($array=[],$mode='every_key'){
$result = false;
if(is_array($array)){
if($mode=='first_key_only'){
if(is_array(array_shift($array))){
$result = true;
}
}
elseif($mode=='every_key'){
$result = true;
foreach($array as $key => $value){
if(!is_array($value)){
$result = false;
break;
}
}
}
elseif($mode=='at_least_one_key'){
if(count($array)!==count($array, COUNT_RECURSIVE)){
$result = true;
}
}
}
return $result;
}
#15
0
Even this works
即使这工作
is_array(current($array));
If false its a single dimension array if true its a multi dimension array.
如果为假,它是一个一维数组,如果为真,它是一个多维数组。
current will give you the first element of your array and check if the first element is an array or not by is_array function.
current将给出数组的第一个元素,并检查第一个元素是否是一个数组,而不是is_array函数。
#16
0
Don't use COUNT_RECURSIVE
不要使用COUNT_RECURSIVE
点击这个网站了解原因
use rsort and then use isset
使用rsort然后使用isset
function is_multi_array( $arr ) {
rsort( $arr );
return isset( $arr[0] ) && is_array( $arr[0] );
}
//Usage
var_dump( is_multi_array( $some_array ) );
#17
0
In my case. I stuck in vary strange condition.
1st case = array("data"=> "name");
2nd case = array("data"=> array("name"=>"username","fname"=>"fname"));
But if data
has array instead of value then sizeof() or count() function not work for this condition. Then i create custom function to check.
If first index of array have value then it return "only value"
But if index have array instead of value then it return "has array"
I use this way
在我的例子中。我陷入了各种奇怪的状况。第一种情况=数组(“data”=>“name”);2例=阵列(“数据”= >数组(“名字”= >“用户名”、“帧”= >“帧”));但是如果数据具有数组而不是值,那么sizeof()或count()函数在这种情况下不起作用。然后我创建自定义函数来检查。如果数组的第一个索引有值那么它返回的是"only value"但是如果索引有数组而不是value那么它返回的是"has array"我用这种方式
function is_multi($a) {
foreach ($a as $v) {
if (is_array($v))
{
return "has array";
break;
}
break;
}
return 'only value';
}
Special thanks to Vinko Vrsalovic
特别感谢Vinko Vrsalovic
#18
-1
if($array[0]){
//enter your code
}
#19
-1
if ( array_key_exists(0,$array) ) {
// multidimensional array
} else {
// not a multidimensional array
}
*only to those arrays with numeric index
*只对具有数值索引的数组
#20
-2
function isMultiArray(array $value)
{
return is_array(reset($value));
}
#21
-3
is_array($arr[key($arr)]);
No loops, plain and simple.
没有循环,简单明了。
Works also with associate arrays not only numeric arrays, which could not contain 0 ( like in the previous example would throw you a warning if the array doesn't have a 0. )
还可以使用关联数组,而不仅仅是不能包含0的数值数组(如前面的示例所示,如果数组没有0,那么将向您抛出一个警告)。