繁体   English   中英

如何区分一维数组与具有相同计数的多维数组?

[英]How to differentiate a 1-dim array from multi-dim array that have the same count?

我有2个潜在的响应数组,我不确定会得到哪一个。 但我知道它将是以下之一:

  • 1-可能包含具有键和值的数组
  • 2-可能仅包含键和值

我的目标是检查我的回答是否属于该类别之一,并以此为依据进行逻辑分析。

我尝试使用PHP count()函数,但是它们都返回2- 值相同

我应该检查些什么才能知道我得到什么类型的响应?

阵列#1

array:2 [▼

  0 => array:2 [▼

        "content" => "Administrator"
        "XSI:TYPE" => "xs:string"

    ]
      1 => array:2 [▼

        "content" => "Read Only"
        "XSI:TYPE" => "xs:string"

    ]
]

阵列#2

array:2 [▼

  "content" => "Read Only"
  "XSI:TYPE" => "xs:string"
]

我同意cmorrissey在评论中提出的方式似乎最好:

因为您知道阵列键,这将是最快的检查方法
if(isset($myArray['content'])){ } else { }


对于您不知道数组键是什么的情况,我以前的回答应该仍然有效:

从数组中获取第一项。

$first = reset($array);

然后算一下。

if (count($first) > 1) {
    // it's like array 1
} else {
    // it's like array 2  ( count($any_string) always returns 1 )
}

您也可以使用is_array($first) 那可能会快一点。

我认为这将帮助您区分两个相同计数的数组。 您可以将COUNT_RECURSIVE标志与count函数一起使用。

在此处尝试此代码段

if(count($array1,COUNT_RECURSIVE)==count($array2,COUNT_RECURSIVE))
{
    echo "Both's value are strings with equal count";
}
elseif(count($array1,COUNT_RECURSIVE)>count($array2,COUNT_NORMAL))
{
    echo "Array one is array of arrays";
}
else
{
    echo "Array two is array of arrays";
}

我知道您需要知道一个数组中是否存在另一个数组。 我有这个可行的解决方案。

我们可以有一个像这样的数组:

$array = array(1, "string", array(1, 2));

它具有整数,字符串和数组。 我们可以使用gettype()函数来获取事物的类型。

在此示例中:

 foreach($array as $row) {
   echo gettype($row) . '<br>';
 }

我们得到下一个结果:

integer
string
array

我们做得到:

foreach($array as $row) {
  if(gettype($row) == 'array') {
    echo "This is an array<br>";
  } else {
    echo "Keep trying guy...<br>";
  }
}

结果将是:

Keep trying guy...
Keep trying guy...
This is an array

希望对您有所帮助,并请记住“爱编码” :)

不能完全确定我是否逐字理解问题,但是我的最初感觉是您要检查父数组是否有任何子数组元素?

那样的话,我想你的意思是?

foreach ($response as $element) {

    if (is_array($element)) {
        // The element is an array
    } else {
        // The element is not an array
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM