Postingan lainnya
Menampilkan value array bersarang
saya ingin menampilkan isi dari array berikut,
<?php
$json='{
"content":[{"ALAMAT": "JL mawar", "TMPT_LHR": "lmpung", "NAMA_LGKP": "RAKA ", "NIK": 4234234234324}],
"copyright": "Kementerian Dalam Negeri "
}';
$data=(json_decode($json, true));
print_r($data);
echo"<br><br>";
echo "<br><br>";
foreach ($data as $key => $value) {
foreach ($value['content'] as $val) {
echo $val['ALAMAT'];
}
}
tampilan error Notice: Undefined index: content in C:\xampp\htdocs\2020\DISDUK_API\coba.php on line 16
Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\2020\DISDUK_API\coba.php on line 16
Warning: Illegal string offset 'content' in C:\xampp\htdocs\2020\DISDUK_API\coba.php on line 16
Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\2020\DISDUK_API\coba.php on line 16
2 Jawaban:
<pre> <?php
$json='{ "content":[{"ALAMAT": "JL mawar", "TMPT_LHR": "lmpung", "NAMA_LGKP": "RAKA ", "NIK": 4234234234324}], "copyright": "Kementerian Dalam Negeri " }'; $data=(json_decode($json, true)); print_r($data);
echo"<br><br>";
echo "<br><br>"; // karna sudah di json decode menjadi array, kita perlu memanggil key content secara langsung foreach ($data['content'] as $values) { // di foreach karena isi dari content adalah array foreach ($values as $value) { echo $value; } } // sama kasusnya, cuma yang ini bisa dipanggil langsung karena sudah berupa string echo $data['copyright']; </pre>
<pre> <?php
$json = '{ "content": [ { "ALAMAT": "JL mawar", "TMPT_LHR": "lmpung", "NAMA_LGKP": "RAKA ", "NIK": 4234234234324 } ], "copyright": "Kementerian Dalam Negeri " }';
$contents = json_decode($json, true)['content'][0];
print_r($contents);
foreach ($contents as $content => $val) { echo $content . ' : ' . $val; echo '<br>'; };
</pre>