简体   繁体   English

为什么is_array()返回false?

[英]Why does is_array() return false?

I have this SimpleXML object: 我有这个SimpleXML对象:

object(SimpleXMLElement)#176 (1) {
 ["record"]=>
 array(2) {
  [0]=>
  object(SimpleXMLElement)#39 (2) {
     ["f"]=>
     array(2) {
       [0]=>
       string(13) "stuff"
       [1]=>
       string(1) "1"
     }
  }
  [1]=>
  object(SimpleXMLElement)#37 (2) {
    ["f"]=>
    array(2) {
      [0]=>
      string(13) "more stuff"
      [1]=>
      string(3) "90"
    }
  }
}

Why does is_array($object->record) return false? 为什么is_array($ object-> record)返回false? It clearly says it's an array. 它清楚地说它是一个阵列。 Why can't I detect it using is_array? 为什么我不能使用is_array检测它?

Also, I am unable to cast it as an array using (array) $object->record. 此外,我无法使用(数组)$ object-> record将其强制转换为数组。 I get this error: 我收到此错误:

Warning: It is not yet possible to assign complex types to properties 警告:尚无法为属性分配复杂类型

SimpleXML nodes are objects that can contain other SimpleXML nodes. SimpleXML节点是可以包含其他SimpleXML节点的对象。 Use iterator_to_array(). 使用iterator_to_array().

It's not an array. 它不是一个数组。 The var_dump output is misleading. var_dump输出具有误导性。 Consider: 考虑:

<?php
$string = <<<XML
<?xml version='1.0'?>
<foo>
 <bar>a</bar>
 <bar>b</bar>
</foo>
XML;
$xml = simplexml_load_string($string);
var_dump($xml);
var_dump($xml->bar);
?>

Output: 输出:

object(SimpleXMLElement)#1 (1) {
  ["bar"]=>
  array(2) {
    [0]=>
    string(1) "a"
    [1]=>
    string(1) "b"
  }
}

object(SimpleXMLElement)#2 (1) {
  [0]=>
  string(1) "a"
}

As you can see by the second var_dump , it is actually a SimpleXMLElement . 正如您在第二个var_dump看到的那样,它实际上是一个SimpleXMLElement

I solved the problem using count() function: 我用count()函数解决了这个问题:

if( count( $xml ) > 1 ) {
    // $xml is an array...
}

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

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