简体   繁体   中英

PHP Cannot use string offset as an array Error

I'm trying to retrieve tasks from Rembmer the Milk API. I run this code:

$array = json_decode($content, true);

foreach($array['rsp']['tasks']['list']['taskseries'] as $keys=>$val) {
$task = $val['name'];
$duedate = $val['task']['due'];
echo $task." ";
echo $duedate."<br>";
}

but I am getting this error:
Fatal error: Cannot use string offset as an array in C:** on line 66
(line 66 being $duedate = $val['task']['due'];)

This is the JSON response I am trying to decode (trying to get "name":"SOMETHING" and "due":"2011-03-17T04:00:00Z":

{"rsp":{"stat":"ok","tasks":{"rev":"[CODE]","list":{"id":"[ID NUMBER]","taskseries": {"id":"ID","created":"DATE CREATED","modified":"DATE","name":"SOMETHING","source":"js","url":"","location_id":"","tags":[],"participants":[],"notes":[],"task":{"id":"ID","due":"2011-03-17T04:00:00Z","has_due_time":"0","added":"DATE","completed":"","deleted":"","priority":"1","postponed":"0","estimate":""}}}}}}

How to fix? Thanks!!!!!

UPDATE This is the JSON response for two or more tasks:

{"rsp":{"stat":"ok","tasks":{"rev":"NUMBER","list":{"id":"ID NUMBER","taskseries":[{"id":"ID NUMBER","created":"CREATED DATE","modified":"DATE","name":"TASK 3","source":"js","url":"","location_id":"","tags":[],"participants":[],"notes":[],"task":{"id":"ID","due":"2011-03-18T04:00:00Z","has_due_time":"0","added":"DATE","completed":"","deleted":"","priority":"1","postponed":"0","estimate":""}},{"id":"ID","created":"DATE","modified":"DATE","name":"SOMETHING","source":"js","url":"","location_id":"","tags":[],"participants":[],"notes":[],"task":{"id":"ID","due":"2011-03-17T04:00:00Z","has_due_time":"0","added":"DATE","completed":"","deleted":"","priority":"1","postponed":"0","estimate":""}}]}}}}

Try this:

$taskSeries=$array['rsp']['tasks']['list']['taskseries'];
if(array_key_exists('id', $taskSeries)) {
    $taskSeries=array($taskSeries);
}
foreach($taskSeries as $task) {
    $name=$task['name'];
    $due=$task['task']['due'];
    // do something with $name and $due here
}

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