Skip to content
Advertisement

How to decode foreach value of array stored in database

This is the print_r($query->getResult()):

Array ( [0] => stdClass Object ( [id] => 9
                                 [user_id] =>
                                 [title] =>
                                 [message] => [{"title":"Nice","option":"Text 1"},{"title":"nice 2","option":"text 2"},{"title":"nice 3","option":"text 3"}]
                                 [created_at] => 2020-06-21 16:59:49
               )
)

I am trying to echo it using:

$query = $db->query("SELECT * from user_msg");

foreach (json_decode($query->getResult()) as $key => $additional_field) {
 
echo $additional_field->title;

}

But unfortunately I got this error:

json_decode() expects parameter 1 to be string, array given

Advertisement

Answer

I don’t know CodeIgnitor, but based on the result array and JSON, you need to do something like this:

foreach ($query->getResult() as $row) {
    foreach(json_decode($row->message) as $msg) {
        echo $msg->title;
    }   
}

Loop each row in the result, decode the message and loop that to get the titles.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement