简体   繁体   中英

Fatal error: Cannot use string offset as an array

  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] => 
        )

}

When I process the sub inner array

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

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

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

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

    }
}

it shows this error

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

how can I avoid that :(

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'];
            }
        }
    }
}

You can test the offset type with the is_array() function. If you want a better answer, post the processing code. Test if $auth[$in] and $autsub[$g] are arrays.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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