Help please, the problem is as follows. I get a string from the json database containing the user id, convert it to an array using json_decode (), delete the id’s name and convert the array back to the json string and when I try to access this string (I get the following error 'Fatal error: Uncaught Error: Cannot use object of type stdClass as array '), but if I delete the last element of the array, then everything is fine. What can be wrong?

public static function DeleteEventByUser($user_id, $news_id) { $user_id = intval($user_id); $news_id = intval($news_id); $link = db::getConnection(); $result = $link->prepare("SELECT `events` FROM `user` WHERE `id` = :user_id"); $result->execute(array('user_id' => $user_id)); $string = $result->fetch(); $record = $string['events']; $massive = json_decode($record); if (is_array($massive) and !empty($massive)) { foreach ($massive as $key => $value) { if ($value == $news_id) { unset($massive[$key]); } } $record = json_encode($massive); $result = $link->prepare("UPDATE `user` SET `events` = :record WHERE `id` = :user_id"); $result->execute(array('record' => $record, 'user_id' => $user_id)); return true; } return false; } 

Error occurs when executing this script.

  public static function addEvent($user_id,$news_id) { $user_id = intval($user_id); $news_id = intval($news_id); $link = db::getConnection(); $result = $link->prepare("SELECT `events` FROM `user` WHERE `id` = :user_id"); $result->execute(array('user_id' => $user_id)); $record = $result->fetch(); $record = $record['events']; if (is_string($record)) { $list = array(); $list = json_decode($record); $list[] = $news_id; $record = json_encode($list); } else { $list = array(); $list[] = $news_id; $record = json_encode($list); } $result = $link->prepare("UPDATE `user` SET `events` = :record WHERE `id` = :user_id"); $result->execute(array('record' => $record, 'user_id' => $user_id)); } 
  • Where exactly does the error occur? - Anton Shchyrov
  • Completed the post code where the error occurs - Morning_star
  • Which line? When performing what operator? - Anton Shchyrov

1 answer 1

Replace this with $list = json_decode($record); to this: $list = json_decode($record, true);

Error due to the result that json_decode returns a stdObject object, and $list[] = ... cannot be used with it.

  • Thank you so much, everything works) - Morning_star