PHP 警告:非法字符串偏移 'tag'

PHP Warning: Illegal string offset 'tag'

我正在尝试修复我刚接触的程序中的一些错误:

if  (strtoupper($xmlnode["tag"])=="RANDOM"){

    $liarray=array();

    $children = $xmlnode["children"];

    for ($randomc=0;$randomc<sizeof($children);$randomc++){
        if (strtoupper($children[$randomc]["tag"]) == "LI"){
            $liarray[]=$randomc;
        }
    }

strtoupper($children[$randomc]["tag"]) 上我得到错误:

Warning: Illegal string offset 'tag'

为什么会这样,我该如何纠正?如果需要,我可以添加更多代码。

你的 $xmlnode['children'] 是字符串,不是数组。

它正在寻找结构如下的内容:

$xmlnode['children'] = [
                            ['tag' => 'LI'],
                            ['tag' => 'LU'],
                            ['tag' => 'LA'],
                            ['tag' => 'LO'],
                            ['tag' => 'LE'],
                            ['tag' => 'LR'],
                        ];

但你实际上给了它 $xmlnode['children'] = "I am a string";

编辑:完整答案:

您首先需要检查 $xmlnode['children'] 数组中的当前项是否是数组,而不是字符串,然后只处理是数组的键。

$xmlnode['tag'] = 'RANDOM';
$xmlnode['children'] = array(
    " ",
    array(
        'tag' => 'li',
        'attributes' => "",
        'value' => "Tell me a story."
    ),
    " ",
    array(
        'tag' => 'li',
        'attributes' => "",
        'value' => "Oh, you are a poet."
    ),
    " ",
    array(
        'tag' => 'li',
        'attributes' => "",
        'value' => "I do not understand."
    ),  
    " "
);

$liarray = array();
if  (strtoupper($xmlnode["tag"]) == "RANDOM") {

    $children = $xmlnode["children"];

    for ($randomc=0; $randomc < sizeof($children); $randomc++) {
        if (is_array($children[$randomc])) {
            if (strtoupper($children[$randomc]["tag"]) == "LI") {
                $liarray[] = $randomc;
            }
        }
    }
    print_r($liarray);  
}