You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

PHP非法偏移类型错误咨询:第9、19行报错原因排查

解决PHP Illegal offset type错误的问题

我一眼就注意到你的代码里有个很容易忽略的语法问题,正是它导致了这个错误:

问题根源:注释位置破坏了数组结构

你在数组定义里把//error here写在了第一个子数组的闭合)后面,并且和[1] =>放在了同一行。PHP的单行注释//会注释掉从它开始到该行末尾的所有内容,这就意味着[1] => Array(...)这整个第二个子数组都被注释掉了!

这样一来,你的$hero数组定义就变成了不完整的结构,PHP解析时会出现语法混乱,后续循环访问数组时自然就触发了Illegal offset type错误——因为此时$hero的结构已经完全不是你预期的三维数组了。

修正方案

首先调整注释位置,确保它不会影响数组的语法结构,同时建议用更简洁的数组写法(去掉不必要的显式数字索引):

// 修正后的数组定义
$hero = [
    [
        ["Superman", "<img src='https://upload.wikimedia.org/wikipedia/en/e/eb/SupermanRoss.png' alt='Superman' title='Superman' style='height:150px;'>", 1],
        ["Batman", "<img src='https://img00.deviantart.net/d9fa/i/2017/079/7/d/batman___transparent_by_asthonx1-db2yliv.png' alt='Batman' title='Batman' style='height:150px;'>", 1],
        ["Flash", "<img src='http://www.pngmart.com/files/2/Flash-Transparent-PNG.png' alt='Flash' title='Flash' style='height:150px;'>", 1],
        ["Aquaman", "<img src='https://vignette.wikia.nocookie.net/deathbattle/images/8/8f/Aquaman_transparent_by_asthonx1-dakip9a.png/revision/latest?cb=20170702181517' alt='Aquaman' title='Aquaman' style='height:150px;'>", 1],
        ["Green Lantern", "<img src='https://orig00.deviantart.net/d594/f/2017/197/4/d/green_lantern_request___transparent_background_by_camo_flauge-dbgi25l.png' alt='Green Lantern' title='Green Lantern' style='height:150px;'>", 1]
    ],
    [
        ["Wolverine", "<img src='https://orig00.deviantart.net/4580/f/2016/274/1/f/wolverine___transparent_by_asthonx1-dajhanh.png' alt='Wolverine' title='Wolverine' style='height:150px;'>", 2],
        ["Ironman", "<img src='http://www.pngmart.com/files/3/Iron-Man-PNG-File.png' alt='Ironman' title='Ironman' style='height:150px;'>", 2],
        ["Ant Man", "<img src='https://orig00.deviantart.net/7ec8/f/2016/092/d/f/ant_man_by_cptcommunist-d9xiez4.png' alt='Ant man' title='Ant man' style='height:150px;'>", 2],
        ["Thor", "<img src='http://www.freepngimg.com/download/thor/3-2-thor-transparent.png' alt='Thor' title='Thor' style='height:150px;'>", 2],
        ["Hulk", "<img src='https://img00.deviantart.net/f71e/i/2016/274/7/8/hulk___transparent_by_asthonx1-dajha0a.png' alt='Hulk' title='Hulk' style='height:150px;'>", 2]
    ]
];

另外,你的循环代码可以优化得更简洁安全,用foreach替代手动计数的for循环,避免重复调用count()

if ($_POST['battle']){
    $n1 = rand(0,5);
    $n2 = rand(6,9);
    echo $n1 , $n2;
    
    foreach ($hero as $row) {
        echo('<tr>');
        foreach ($row as $heroData) {
            echo('<td>' . $heroData[1] . '</td>');
        }
        echo('</tr>');
    }
}

这样调整后,数组结构正确,循环逻辑更清晰,就不会再出现Illegal offset type错误了。

内容的提问来源于stack exchange,提问作者Ethan Callanan

火山引擎 最新活动