Faisal
Faisal

Reputation: 408

How to decode this json with foreach

This is the JSON

{
  "circuit_list": [
    {
      "_id": "58c0f378a986f808cdaf94cf", 
      "aggregation": {
        "dev_name": "ME2-D2-BOO", 
        "port": {
          "desc": "AKSES_SITE_SITE-TSEL_ME2-D2-BOO#1/2/5_200M_BOO082#CIPAKUBOO534", 
          "name": "1/2/5"
        }
      }, 
      "area": "AREA 2", 
      "site_id": "N/A", 
      "site_name": "N/A"
    }, 
    {
      "_id": "58c0f378a986f808cdaf94d0", 
      "aggregation": {
        "dev_name": "ME2-D2-BOO", 
        "port": {
          "desc": "AKSES_SITE_SITE-TSEL_ME2-D2-BOO#1/2/5_200M_BOO082#CIPAKUBOO534", 
          "name": "1/2/5"
        }
      }, 
      "area": "AREA 2", 
      "site_id": "N/A", 
      "site_name": "N/A"
    }
}

I already try with this code

$json = json_decode($url, true);

foreach($json as $value)
{
    $_id = $value->_id;

}

it didn't work. Please help, I need to get the value to show them on the view. Did I do this wrong? this json is difficult because i didn't understand the structure. I usually decode json with format

[{"id":"1","name":"faisal"}]

like this and with my foreach it's working.

Upvotes: 1

Views: 58

Answers (2)

Rushil K. Pachchigar
Rushil K. Pachchigar

Reputation: 1321

<?php
$json = json_decode($url,true);
foreach($json['circuit_list'] as $value) 
{
    $id = $value['_id'];
}

?>

Upvotes: 2

Jerodev
Jerodev

Reputation: 33186

If the second parameter of json_decode is true, the function will return an array instead of an object. Also, you would need to loop over the circuit_list property of the object.

$json = json_decode($url); // <- remove the parameter

foreach($json->circuit_list as $value) // <- loop over circuit_list
{
    $_id = $value->_id;
}

Upvotes: 3

Related Questions