致命错误:无法使用字符串作为数组offset [英] Fatal error: Cannot use string offset as an array

查看:156
本文介绍了致命错误:无法使用字符串作为数组offset的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  Array
(
    [0] => Array
        (
            [auth_id] => 1
            [auth_section] => Client Data Base
            [auth_parent_id] => 0
            [auth_admin] => 1
            [sub] => Array
                (
                    [0] => Array
                        (
                            [auth_id] => 2
                            [auth_section] => Client Contact
                            [auth_parent_id] => 1
                            [auth_admin] => 1
                        )

                )

        )

    [1] => Array
        (
            [auth_id] => 6
            [auth_section] => All Back Grounds
            [auth_parent_id] => 0
            [auth_admin] => ,4
            [sub] => Array
                (
                    [0] => Array
                        (
                            [auth_id] => 7
                            [auth_section] => Edit Custom
                            [auth_parent_id] => 6
                            [auth_admin] => 1
                        )
                )

        )

    [2] => Array
        (
            [auth_id] => 20
            [auth_section] => Order Mail
            [auth_parent_id] => 0
            [auth_admin] => 1
            [sub] => 
        )

}

当我处理子内阵列

for($in=0 ; $in < count($auth); $in++){

    $autsub     =   $auth[$in]["sub"];

    for($g=0 ; $g<count($autsub); $g++){

        echo $autsub[$g]["auth_id"];

    }
}

这表明这个错误

致命错误:无法使用字符串作为数组offset .........

Fatal error: Cannot use string offset as an array.........

我怎样才能避免这种情况:(

how can I avoid that :(

推荐答案

的问题是,在数组中的最后一项( 2 )不具有数组,但你想无论如何访问它。你需要检查项存在,如果它在循环之前的数组。这里使用一个例子的foreach

The problem is that the last entry in the array (2) does not have a sub array, but you're trying to access it anyway. You'll need to check if the entry exists and if it's an array before looping over it. Here an example using foreach:

foreach ($array as $auth) {
    if (!empty($auth['sub']) && is_array($auth['sub'])) {
        foreach ($auth['sub'] as $sub) {
            if (!empty($sub['auth_id'])) {
                echo $sub['auth_id'];
            }
        }
    }
}

这篇关于致命错误:无法使用字符串作为数组offset的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆