How to retrieve Nested JSON in Codeigniter PHP

Viewed 33

I have JSON like

{
 "data": [
   {
     "id": 1,
     "attributes": {
       "Name": "Paket Hemat",
       "Description": "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries",
       "Price": 120000,
       "Image": null,
       "createdAt": "2022-09-17T04:59:23.734Z",
       "updatedAt": "2022-09-17T05:44:52.521Z",
       "publishedAt": "2022-09-17T04:59:26.460Z"
     }
   },
   {
     "id": 2,
     "attributes": {
       "Name": "Paket Medium",
       "Description": "Loren ipsum qqiqqfqqv",
       "Price": 120000,
       "Image": null,
       "createdAt": "2022-09-17T05:44:18.713Z",
       "updatedAt": "2022-09-17T05:44:20.723Z",
       "publishedAt": "2022-09-17T05:44:20.720Z"
     }
   }
 ],
 "meta": {
   "pagination": {
     "page": 1,
     "pageSize": 25,
     "pageCount": 1,
     "total": 2
   }
 }
}

Then i would like to retrieve that as row using this


   if(isset($data)){
   $hasil = json_decode($data);
   foreach($hasil as $row){
     echo $row['id'];

But when i execute it, give me error enter image description here

I have tried to using $row->id and $row['id'] but it can't solve the issue

Please advice

1 Answers

First change

$hasil = json_decode($data);

To

$hasil = json_decode($data,1);
foreach($hasil['data'] as $id => $row){
  echo "$id\n";
}

In the foreach loop you can access the the values with these variables:

$Name = $hasil['data']['attributes'][$key]['attributes']['Name'];
$Description = $hasil['data']['attributes'][$key]['attributes']['Description'];
$Price = $hasil['data']['attributes'][$key]['attributes']['Price'];
$Image = $hasil['data']['attributes'][$key]['attributes']['Image'];
$updatedAt = $hasil['data']['attributes'][$key]['attributes']['updatedAt'] ;
$publishedAt = $hasil['data']['attributes'][$key]['attributes']['publishedAt'] ;

It's almost 4:00 am and I have not slept yet.
Hopefully I did not make a mistake.
I do not think I did but I'm old and tired.
If I did make a mistake it should be easy to fix
G'Nite.

Related