Cenk YAGMUR
Cenk YAGMUR

Reputation: 3451

Php Json Get Value Array Index?

I have this code:

{"DT_RowId":"row_8","siparisler":{"id":"8","tarih":"14-12-2015","uid":"118","mid":"4","satis_fiyati":"5","adet":"7","odeme":"1","olusturan":"ares","sonduzenleyen":""},"urunler":{"urun_adi":"BANNER 100 AH","stok_kodu":"10010"},"musteriler":{"unvan":"3A Otomotiv San. Tic. Ltd. \u015eti."},"kdvsiz":"4.23728813559","kdv":"0.762711864407","top":"35"}

How can get siparisler id with array index?

$result2 = json_decode ($val,true);
return $result2[1][0];

I want to get that with array index because my JSON names are always different.

or how can i get second array name for if control ?

Upvotes: 0

Views: 5244

Answers (1)

Fabian Schmengler
Fabian Schmengler

Reputation: 24551

you could use array_values() to normalize the arrays:

return array_values(array_values(json_decode($val, true))[1])[0];

array_values() returns all the values from the array and indexes the array numerically.

The same split into multiple statements to be more clear:

$result = json_decode($val, true);
$result = array_values($result)[1];
$result = array_values($result)[0];
return $result;

Or for PHP 5.3 and below:

$result = json_decode($val, true);
$result = array_values($result);
$result = array_values($result[1]);
return $result[0];

Upvotes: 2

Related Questions