以下是json文件的一部分:
{
"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
}
]
}
]
}
这是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 as $row) {
echo '<div>';
$FabrikatNavn = $row->FabrikatNavn;
$ModelNavn = $row->ModelNavn;
$PrisDetailDkk = $row->PrisDetailDkk;
// tried this, but it don't work -->
foreach($row->StatusTyper as $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>';
}
正如你所看到的,“StatusTyper”中的值不同,所以在这里我尝试了if else,但我无法让它工作 - 它每次都返回''' 怎么了?
答案 0 :(得分:1)
这是因为循环总是选择最后一个条件的值。如果找到匹配项$StausId == "-15"
,您需要以某种方式告诉PHP break循环,否则它将继续匹配$StausId != "-15"
,它始终将值"um"
赋给$Moms
}。
foreach($row->StatusTyper as $StatusTyper) {
$StausId = $StatusTyper->StatusId;
if ($StausId == "-15") {
// Found the match
$Moms = 'mm';
// End the execution of current loop
break;
} else {
// $StausId value is not equal to -15
// So it was picking this
$Moms = 'um';
}
}