检查数组是否是多维的?

发布于 2024-07-07 01:36:37 字数 150 浏览 7 评论 0原文

  1. 检查数组是否为平面数组的最有效方法是什么
    原始值还是一个多维数组
  2. 有没有办法在不实际循环的情况下做到这一点
    array 并对其每个元素运行 is_array()
  1. 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?
  2. Is there any way to do this without actually looping through an
    array and running is_array() on each of its elements?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(16

绝對不後悔。 2024-07-14 01:36:37

使用 count() 两次; 一次在默认模式下,一次在递归模式下。 如果值匹配,则该数组不是多维,因为多维数组将具有更高的递归计数。

if (count($array) == count($array, COUNT_RECURSIVE)) 
{
  echo 'array is not multidimensional';
}
else
{
  echo 'array is multidimensional';
}

该选项第二个值mode是在 PHP 4.2.0 中添加的。 来自 PHP 文档

如果可选模式参数设置为 COUNT_RECURSIVE(或 1),count() 将以递归方式对数组进行计数。 这对于计算多维数组的所有元素特别有用。 count() 不检测无限递归。

但是此方法不会检测array(array())

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.

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:

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.

However this method does not detect array(array()).

早乙女 2024-07-14 01:36:37

简短的答案是否定的,如果“第二维度”可能在任何地方,那么如果不至少隐式循环,您就无法做到这一点。 如果它必须在第一项中,你就这样做

is_array($arr[0]);

但是,我能找到的最有效的通用方法是在数组上使用 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

隐式循环,但我们不能在找到匹配项后立即短路...

$ 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)

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()):

$ 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)
只等公子 2024-07-14 01:36:37

对于 PHP 4.2.0 或更高版本:

function is_multi($array) {
    return (count($array) != count($array, 1));
}

For PHP 4.2.0 or newer:

function is_multi($array) {
    return (count($array) != count($array, 1));
}
╄→承喏 2024-07-14 01:36:37

我认为这是最直接的方法,也是最先进的:

function is_multidimensional(array $array) {
    return count($array) !== count($array, COUNT_RECURSIVE);
}

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);
}
愁杀 2024-07-14 01:36:37

PHP 7 之后你可以简单地这样做:

public function is_multi(array $array):bool
{
    return is_array($array[array_key_first($array)]);
}

After PHP 7 you could simply do:

public function is_multi(array $array):bool
{
    return is_array($array[array_key_first($array)]);
}
清风挽心 2024-07-14 01:36:37

您可以检查第一个元素的 is_array() ,假设如果数组的第一个元素是数组,那么其余元素也是数组。

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.

我最亲爱的 2024-07-14 01:36:37

我想你会发现这个功能是最简单、最高效、最快的方式。

function isMultiArray($a){
    foreach($a as $v) if(is_array($v)) return TRUE;
    return FALSE;
}

你可以这样测试:

$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';

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';
时光沙漏 2024-07-14 01:36:37

不要使用 COUNT_RECURSIVE

点击此网站了解原因

使用 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 ) );

Don't use COUNT_RECURSIVE

click this site for know why

use rsort and then use isset

function is_multi_array( $arr ) {
rsort( $arr );
return isset( $arr[0] ) && is_array( $arr[0] );
}
//Usage
var_dump( is_multi_array( $some_array ) );
夏の忆 2024-07-14 01:36:37

即使这样,

is_array(current($array));

如果false它是一个单维数组,如果true它是一个多维数组。

current 将为您提供数组的第一个元素,并通过 is_array 函数检查第一个元素是否是数组。

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.

断爱 2024-07-14 01:36:37

您还可以像这样进行简单的检查:

$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

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
缘字诀 2024-07-14 01:36:37

我认为这个很优雅(向另一位我不知道他的用户名的用户提供支持):

static public function isMulti($array)
{
    $result = array_unique(array_map("gettype",$array));

    return count($result) == 1 && array_shift($result) == "array";
}

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";
}
笔落惊风雨 2024-07-14 01:36:37

就我而言。 我陷入了各种奇怪的状况。
第一种情况 = array("data"=> "name");
第二种情况 = array("data"=> array("name"=>"username","fname"=>"fname"));
但是,如果 data 有数组而不是值,则 sizeof() 或 count() 函数不适用于这种情况。 然后我创建自定义函数来检查。

如果数组的第一个索引有值,那么它返回“唯一值”
但如果索引有数组而不是值,那么它返回“有数组”
我使用这种方式

 function is_multi($a) {
        foreach ($a as $v) {
          if (is_array($v)) 
          {
            return "has array";
            break;
          }
          break;
        }
        return 'only value';
    }

特别感谢 Vinko Vrsalovic

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

 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

徒留西风 2024-07-14 01:36:37

它就像

$isMulti = !empty(array_filter($array, function($e) {
                    return is_array($e);
                }));

Its as simple as

$isMulti = !empty(array_filter($array, function($e) {
                    return is_array($e);
                }));
幼儿园老大 2024-07-14 01:36:37

此函数将返回 int 数组维度数(从 此处)。

function countdim($array)
{
   if (is_array(reset($array))) 
     $return = countdim(reset($array)) + 1;
   else
     $return = 1;
 
   return $return;
}

This function will return int number of array dimensions (stolen from here).

function countdim($array)
{
   if (is_array(reset($array))) 
     $return = countdim(reset($array)) + 1;
   else
     $return = 1;
 
   return $return;
}
自此以后,行同陌路 2024-07-14 01:36:37

尝试如下

if (count($arrayList) != count($arrayList, COUNT_RECURSIVE)) 
{
  echo 'arrayList is multidimensional';

}else{

  echo 'arrayList is no multidimensional';
}

Try as follows

if (count($arrayList) != count($arrayList, COUNT_RECURSIVE)) 
{
  echo 'arrayList is multidimensional';

}else{

  echo 'arrayList is no multidimensional';
}
半葬歌 2024-07-14 01:36:37
$is_multi_array = array_reduce(array_keys($arr), function ($carry, $key) use ($arr) { return $carry && is_array($arr[$key]); }, true);

这是一个很好的衬里。 它迭代每个键以检查该键的值是否是数组。 这将确保真实

$is_multi_array = array_reduce(array_keys($arr), function ($carry, $key) use ($arr) { return $carry && is_array($arr[$key]); }, true);

Here is a nice one liner. It iterates over every key to check if the value at that key is an array. This will ensure true

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文