简体   繁体   中英

PHP Fatal error: Cannot use string offset as an array

Facing a weird situation with arrays.. I am using LinkedIn API to get profile info which returns data in two formats..

If user has just one educational item

educations=>education=>school-name
educations=>education=>date
...

If more than one education item

educations=>education=>0=>school-name
educations=>education=>0=>date
...
educations=>education=>1=>school-name
educations=>education=>1=>date
...

Now I am trying to make it consistent and convert

educations=>education=>school-name

to

educations=>education=>0=>school-name

But getting error in code that i believe should work

if(empty($educations['education'][0]['school-name']))
{
    $temp = array();
    $temp['education'][0]=$educations['education'];
    $educations = $temp;
}

This fails for "just one educational item", generates error on the first line for (isset,is_array and empty)

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

print_r returns

[educations] => Array
    (
        [education] => Array
            (
                     [id] => 109142639
                     [school-name] => St. Fidelis College
                     [end-date] => Array
                         (
                             [year] => 2009
                         )

            )

    )

Usually you'd write the assignment like this:

$temp = array(
    "education" => array($educations['education'])
);

To avoid any issues with indexes. This might also fix yours.

If you're unsure about the contents of $educations['education'][0]['school-name'] you can simply check each part:

if(isset($educations['education'], $educations['education'][0], $educations['education'][0]['school-name']))

This works because isset doesn't behave like a normal function. It takes multiple arguments in a lazy manner.

You want:

if(array_key_exists('school-name',$educations['education']))
{
    $educations['education'] = array($educations['education']);
}

Today I experienced the same problem in my application. Fatal error: Cannot use string offset as an array in /home/servers/bf4c/bf4c.php on line 2447

line 2447

if (!isset($time_played[$player]["started"])) {
                    $time_played[$player]["started"] = $time;
                }

$time_played was overwritten elsewhere and defined as a string. So make sure you do use unique variable names.

Here's a tip if you're running through a loop, and it breaks:

 if( $myArray != "" ){ // Do your code here echo $myArray['some_id']; } 

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