0

I have a JSON, and I would like to get the value of JSON as a PHP varible. If I echoing variable $jne the result will be like this.

{
"rajaongkir":{
  "query":{
     "origin":"501",
     "destination":"114",
     "weight":1700,
     "courier":"jne"
  },
  "status":{
     "code":200,
     "description":"OK"
  },
  "origin_details":{
     "city_id":"501",
     "province_id":"5",
     "province":"DI Yogyakarta",
     "type":"Kota",
     "city_name":"Yogyakarta",
     "postal_code":"55000"
  },
  "destination_details":{
     "city_id":"114",
     "province_id":"1",
     "province":"Bali",
     "type":"Kota",
     "city_name":"Denpasar",
     "postal_code":"80000"
  },
  "results":[
     {
        "code":"jne",
        "name":"Jalur Nugraha Ekakurir (JNE)",
        "costs":[
           {
              "service":"OKE",
              "description":"Ongkos Kirim Ekonomis",
              "cost":[
                 {
                    "value":38000,
                    "etd":"4-5",
                    "note":""
                 }
              ]
           },
           {
              "service":"REG",
              "description":"Layanan Reguler",
              "cost":[
                 {
                    "value":44000,
                    "etd":"2-3",
                    "note":""
                 }
              ]
           },
           {
              "service":"SPS",
              "description":"Super Speed",
              "cost":[
                 {
                    "value":349000,
                    "etd":"",
                    "note":""
                 }
              ]
           },
           {
              "service":"YES",
              "description":"Yakin Esok Sampai",
              "cost":[
                 {
                    "value":98000,
                    "etd":"1-1",
                    "note":""
                 }
              ]
           }
        ]
     }
  ]
 }
 }

this is how I try to get the value, I want to get the 'value' inside the 'cost'

$content = $jne;
$json = json_decode($content, true);

$value = $json[results][0][costs][1][cost][0][value];

Thanks for your help..

Eka Soedono
  • 41
  • 1
  • 10

2 Answers2

4

If you are looking for the value "44000", then your query should be:

$value = $json['rajaongkir']['results'][0]['costs'][1]['cost'][0]['value'];
Jake Opena
  • 1,475
  • 1
  • 11
  • 18
3

There are more than one "value" there. This will give you all 4 values there:

$json = json_decode($content, true);

$values = Array();
foreach($json['rajaongkir']['results'][0]['costs'] as $cost) {
    $values[] = $cost['cost'][0]['value'];
}
print_r($values);

Outputs:

Array
(
    [0] => 38000
    [1] => 44000
    [2] => 349000
    [3] => 98000
)
Ulver
  • 905
  • 8
  • 13