使用If语句更改数组输出

时间:2018-08-17 19:35:34

标签: php html arrays api

我是API集成和PHP的新手。我最近将VIN解码器集成到我的应用中。在输入框中输入车辆的VIN,选择“提交”,然后会显示API数据库中有关该车辆的所有信息。

数据与类别及其对应的元素一起存储为关联数组。例如,对于VIN:WAUBFAFL6FA058452,类别之一是Make,其元素是Audi。

某些VIN携带的数据比其他VIN多。我只希望选择提交时显示带有数据的类别。因此,在一些帮助下,我添加了以下代码行:

    foreach ($json['Results'][0] as $k => $v){
  if (!empty($v)) {
    $results .= ($k).": ".($v).'<br />';
    }

这是输出的样子:

AirBagLocCurtain: All Rows
AirBagLocFront: 1st Row (Driver & Passenger)
AirBagLocSide: 1st Row (Driver & Passenger)
BodyClass: Sedan/Saloon
DisplacementCC: 1984
DisplacementCI: 121.071108283
DisplacementL: 1.984000
Doors: 4
EngineCylinders: 4
EngineHP: 220
EngineKW: 164.0540
EngineManufacturer: Audi
EngineModel: Flex Fuel Capable engine
ErrorCode: 0 - VIN decoded clean. Check Digit (9th position) is correct
FuelTypePrimary: Gasoline
FuelTypeSecondary: Ethanol (E85)
Make: AUDI
Manufacturer: AUDI
ManufacturerId: 1149
Model: A4
ModelYear: 2015
OtherEngineInfo: Fuel: Gas (50-St); Federal / California Emission Standard: BIN 5 / ULEV II; Emissions Certification Test Group: FVGAV02.0AUB / FVGAJ02.0AUF E85
PlantCity: Ingolstadt
PlantCountry: Germany
SeatBeltsAll: Manual
Series: Premium quattro
TPMS: Indirect
TransmissionStyle: Automatic
VIN: WAUBFAFL6FA058452
VehicleType: PASSENGER CAR

我下一步要做的是编辑类别名称。例如:将ModelYear更改为Year,将TransmissionStyle更改为Transmission Type,将EngineHP更改为Horsepower,等等。我尝试添加$ k作为变量的简单IF语句;但是,这没有用。您将在下面的PHP代码中看到这种尝试。有关如何编辑类别名称的任何想法?

这是我的html,它是一个简单的输入栏和提交按钮:

<!DOCTYPE html>
<html>

<head>
<title>VIN Decoder API Test</title>

<style type="text/css">
input,button {width: 200px;display: block;margin-left: auto;margin-right: auto;}
button {width: 100px;background-color: darkgray;}
</style>

</head>

<body>

    <form action="processvin3.php" method="post">

    <input type="text" id="b12" placeholder="Enter VIN" name="b12" maxlength="100"/>
    <br>
    <button id="submit_btn">Submit</button>

  </form>

  <br>
  <br>

</body>
</html>

还有我的PHP

<?php

$vin = $_POST["b12"];

if ($vin) {
$postdata = http_build_query([
        'format' => 'json',
        'data' => $vin
    ]
);
$opts = [
    'http' => [
        'method' => 'POST',
        'content' => $postdata
    ]
];

$apiURL = "https://vpic.nhtsa.dot.gov/api/vehicles/DecodeVINValuesBatch/";
$context = stream_context_create($opts);
$fp = fopen($apiURL, 'rb', false, $context);
$line_of_text = fgets($fp);
$json = json_decode($line_of_text, true);
fclose($fp);

foreach ($json['Results'][0] as $k => $v){
  if (!empty($v)) {
    $results .= ($k).": ".($v).'<br />';
    }
    if ($k == "ModelYear"){
      $k  = "Year";
    }
  }

  echo $results;
  }

else {
echo 'No Vin Inputted';
  }

?>

非常感谢您可以提供的任何帮助。

1 个答案:

答案 0 :(得分:1)

我建议使用查找数组而不是一系列条件语句。

代码:(Demo

$json['Results'][0] = [
    'AirBagLocCurtain' => 'All Rows',
    'AirBagLocFront' => '1st Row (Driver & Passenger)',
    'AirBagLocSide' => '1st Row (Driver & Passenger)',
    'BodyClass' => 'Sedan/Saloon',
    'DisplacementCC' => '1984',
    'DisplacementCI' => '121.071108283',
    'DisplacementL' => '1.984000',
    'Doors' => '4',
    'EngineCylinders' => '4',
    'EngineHP' => '220',
    'EngineKW' => '164.0540',
    'EngineManufacturer' => 'Audi',
    'EngineModel' => 'Flex Fuel Capable engine',
    'ErrorCode' => '0 - VIN decoded clean. Check Digit (9th position) is correct',
    'FuelTypePrimary' => 'Gasoline',
    'FuelTypeSecondary' => 'Ethanol (E85)',
    'Make' => 'AUDI',
    'Manufacturer' => 'AUDI',
    'ManufacturerId' => '1149',
    'Model' => 'A4',
    'ModelYear' => '2015',
    'OtherEngineInfo' => 'Fuel: Gas (50-St); Federal / California Emission Standard: BIN 5 / ULEV II; Emissions Certification Test Group: FVGAV02.0AUB / FVGAJ02.0AUF E85',
    'PlantCity' => 'Ingolstadt',
    'PlantCountry' => 'Germany',
    'SeatBeltsAll' => 'Manual',
    'Series' => 'Premium quattro',
    'TPMS' => 'Indirect',
    'TransmissionStyle'=> 'Automatic',
    'VIN' => 'WAUBFAFL6FA058452',
    'VehicleType' => 'PASSENGER CAR'
];

$lookup = [
    'ModelYear' => 'Year',
    'TransmissionStyle' => 'Transmission Type',
    'EngineHP' => 'Horsepower'
];

foreach ($json['Results'][0] as $k => $v) {
    if (!empty($v)) {
        $result[] = (isset($lookup[$k]) ? $lookup[$k] : $k) . ": $v";
    }
}
// alphabetize new keys now with sort() if desired
echo implode("<br>", $result);

现在我看到了your new project requirementsif/elseif块更适合(因为有条件的round()调用)。

代码:(Demo

foreach ($json['Results'][0] as $k => $v){
    if (strlen($v)) {  // only bother to process this element if it contains a value with a positive length
        if ($k == "DisplacementCC") {
            $results[]  = "Engine Displacement 2: $v cc's";
        } elseif ($k == "DisplacementCI") {
            $results[] = "Engine Displacement 3: $v ci's";
        } elseif ($k == "DisplacementL") {
            $results[] = "Engine Displacement 1: " . round($v, 1) . " liters";
        } elseif ($k == "EngineKW") {
            $results[] = "Kilowatts: $v kw";
        } elseif ($k == "EngineManufacturer") {
            $results[] = "Engine Manufacturer: $v";
        } elseif ($k == "EngineModel") {
            $results[] = "Engine Model: $v";
        } elseif ($k == "FuelTypePrimary") {
            $results[] = "Primary Fuel Type: $v";
        } elseif ($k == "FuelTypeSecondary") {
            $results[] = "Secondary Fuel Type: $v";
        } elseif ($k == "EngineHP") {
            $results[] = "Horsepower: $v hp";
        } elseif ($k == "EngineCylinders") {
            $results[] = "Engine Size: $v cylinders";
        }
    }
}

echo "<div id=\"VIN\">{$json['Results'][0]['VIN']}</div>";
echo "<div id=\"EngineDetails\">";
    echo "Engine-<br /><br />";
    echo implode("<br />", $results);
echo "</div>";