Fatal error: cannot use line 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 an additional internal array

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

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

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

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

    }
}

he shows this error

Fatal error: cannot use line offset as an array .........

how can i avoid this :(

+3
source share
2 answers

The problem is that the last entry in array ( 2) does not have an array sub, but you are still trying to access it. You will need to check if the record exists and if it is an array before iterating through it. Here's 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'];
            }
        }
    }
}
+9
source

is_array(). , . , $auth [$ in] $autsub [$ g] .

0

Source: https://habr.com/ru/post/1750448/


All Articles