非法偏移类型 php 函数


Illegal offset type php function

我得到了这个代码,但由于非法偏移类型而遇到问题。

function getChildren($xmlSet){
    global $output;
    if(is_object($xmlSet)){
         if(count($xmlSet->children()) > 0){
             foreach($xmlSet->children() as $i => $child){
                  if($child->getName() === "label"){
                       $output[(string)$xmlSet->attributes()['id']] = getChildren($child);
                  } else {
                       if($child->getName() === "field" || $child->getName() === "fieldset"){
                            $output[$xmlSet->attributes()['id']] = getChildren($child);
                       }
                  }
             }

你有过一次

 $output[(string)$xmlSet->attributes()['id']] = getChildren($child);

但第二次你有

 $output[$xmlSet->attributes()['id']] = getChildren($child);

第一次显式强制转换为字符串,但第二次隐式地这样做,因此发出警告。

某些对象类型,例如SimpleXMLElement对象类型,将通过魔术方法__toString()返回字符串表示以打印/回显,但不能作为常规字符串。尝试将它们用作数组键将产生非法偏移类型错误,除非您通过 (string)$obj (ref) 将它们转换为正确的字符串

问题是您尝试通过 simpleXml 对象访问数组元素。在访问数组元素之前,必须将其强制转换为标量类型值。

所以改变这个:

$output[$xmlSet->attributes()['id']] = getChildren($child);

对此:

$output[(string)$xmlSet->attributes()['id']] = getChildren($child);