PHP foreach - parsed json from an array inside an array -
here part of json file:
{ "status": { "http_code": 200 }, "contents": [ { "fabrikatnavn": "jaguar", "modelnavn": "420g", "prisdetaildkk": 119900, "statustyper": [ { "statusid": -5, "statusnavn": "benzin" }, { "statusid": -15, "statusnavn": "momsfri" }, { "statusid": -11, "statusnavn": "100-120.000" } ], "imageids": [ { "id": 79359 }, { "id": 79360 }, { "id": 79361 }, { "id": 79370 } ] }, { "fabrikatnavn": "opel", "modelnavn": "corsa", "prisdetaildkk": 135900, "statustyper": [ { "statusid": -4, "statusnavn": "diesel" }, { "statusid": -15, "statusnavn": "momsfri" }, { "statusid": -12, "statusnavn": "120-140.000" } ], "imageids": [ { "id": 225794 }, { "id": 225795 }, { "id": 225796 }, { "id": 225797 } ] }, { "fabrikatnavn": "hyundai", "modelnavn": "h1", "prisdetaildkk": 14999, "statustyper": [ { "statusid": 13, "statusnavn": "afhentning" }, { "statusid": -4, "statusnavn": "diesel" }, { "statusid": -8, "statusnavn": "0-60.000" } ], "imageids": [ { "id": 415605 }, { "id": 415606 }, { "id": 415607 }, { "id": 415979 } ] } ] }
and here's php
<?php $url = 'http://banen.klintmx.dk/json/ba-simple-proxy.php?url=api.autoit.dk/car/getcarsextended/59efc61e-ceb2-463b-af39-80348d771999'; $json= file_get_contents($url); $data = json_decode($json); $rows = $data->{'contents'}; foreach ($rows $row) { echo '<div>'; $fabrikatnavn = $row->fabrikatnavn; $modelnavn = $row->modelnavn; $prisdetaildkk = $row->prisdetaildkk; // tried this, don't work --> foreach($row->statustyper $statustyper) { $stausid = $statustyper->statusid; if ($stausid == '-15') { $moms = 'mm'; } else { $moms = 'um'; } } echo '<div class=" ' . $moms . ' "> '; echo $fabrikatnavn . $modelnavn . ' pris ' . $prisdetaildkk; echo '</div>'; echo '</div>'; }
as can see, values in "statustyper" different, here have tried if else, can not work - returns'um' everytime what's wrong?
this because loop picks value of last condition met. need somehow tell php break loop if founds match $stausid == "-15"
otherwise continue match $stausid != "-15"
assigns value "um"
$moms
.
foreach($row->statustyper $statustyper) { $stausid = $statustyper->statusid; if ($stausid == "-15") { // found match $moms = 'mm'; // end execution of current loop break; } else { // $stausid value not equal -15 // picking $moms = 'um'; } }
Comments
Post a Comment