更改API数据输出的布局

时间:2018-08-17 16:03:57

标签: php html arrays api

我是API集成和PHP的新手。我最近将VIN解码器集成到我的应用中。在输入框中输入车辆的VIN,然后选择Submit(提交),并显示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
And so on....

如何更改此布局?我希望将输出布局更改为以下内容。

所需的输出:

VIN: WAUBFAFL6FA058452

General – 
Make: AUDI
ModelYear: 2015
Model: A4
BodyClass: Sedan/Saloon
Doors: 4
Series: Premium quattro
VehicleType: PASSENGER CAR

Safety - 
AirBagLocCurtain: All Rows
AirBagLocFront: 1st Row (Driver & Passenger)
AirBagLocSide: 1st Row (Driver & Passenger)
SeatBeltsAll: Manual

Engine - 
DisplacementCC: 1984
DisplacementCI: 121.071108283
DisplacementL: 1.984000
EngineCylinders: 4
EngineHP: 220
EngineKW: 164.0540
EngineManufacturer: Audi
EngineModel: Flex Fuel Capable engine
TransmissionStyle: Automatic
OtherEngineInfo: Fuel: Gas (50-St); Federal / California Emission        Standard: BIN 5 / ULEV II; Emissions Certification Test Group: FVGAV02.0AUB / FVGAJ02.0AUF E85
FuelTypePrimary: Gasoline
FuelTypeSecondary: Ethanol (E85)

Factory - 
Manufacturer: AUDI
ManufacturerId: 1149
PlantCity: Ingolstadt
PlantCountry: Germany

Other - 
ErrorCode: 0 - VIN decoded clean. Check Digit (9th position) is correct
TPMS: Indirect

这是我的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 />';
      }
    }

    echo $results;
  }

    else {
    echo 'No Vin Inputted';
    }




?>

任何建议,技巧或答案将不胜感激。非常感谢。

2 个答案:

答案 0 :(得分:0)

您以一个良好的开端

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

但是在开始输出输出之前,请尝试创建自己的数组

$data = array();
foreach ($json['Results'][0] as $k => $v){
      if (!empty($v)) {
        $data[$k] = $v;
      }
    }

然后,您可以花些时间回显所需的列表。 通过这种简单的方法,希望空白列表中排除的列表中您想要的字段非常低。然后,您必须对此做些事情。

echo 'Make: '. $data['Make'] . '<br>';
echo 'ModelYear: '. $data['ModelYear']. '<br>';
echo 'Model: '. $data['Model']. '<br>';
echo 'BodyClass: '. $data['BodyClass']. '<br>';
echo 'Doors: '. $data['Doors']. '<br>';
echo 'Series: '. $data['Series']. '<br>';
echo 'VehicleType: '. $data['VehicleType']. '<br>';

您还可以仅使用键和空白值手动构建所需的数据数组,然后允许您的foreach填充它。然后,您可以使用另一个Forech来打印数据阵列,因为它会按您期望的顺序进行。

只是一个建议。希望它可以帮助您在过程中更进一步。

答案 1 :(得分:0)

我建议使用“主”数组来过滤和准备按类别分组的数据。有关更多说明,请参见内联注释:

代码:(Demo

您的主阵列:

$master = [
    "General" => [
        "Make" => "",
        "ModelYear" => "",
        "Model" => "",
        "BodyClass" => "",
        "Doors" => "",
        "Series" => "",
        "VehicleType" => ""
    ],
    "Safety" => [
        "AirBagLocCurtain" => "",
        "AirBagLocFront" => "",
        "AirBagLocSide" => "",
        "SeatBeltsAll" => ""
    ],
    "Engine" => [
        "DisplacementCC" => "",
        "DisplacementCI" => "",
        "DisplacementL" => "",
        "EngineCylinders" => "",
        "EngineHP" => "",
        "EngineKW" => "",
        "EngineManufacturer" => "",
        "EngineModel" => "",
        "TransmissionStyle" => "",
        "OtherEngineInfo" => "",
        "FuelTypePrimary" => "",
        "FuelTypeSecondary" => ""
    ],
    "Factory" => [
        "Manufacturer" => "",
        "ManufacturerId" => "",
        "PlantCity" => "",
        "PlantCountry" => ""
    ],
    "Other" => [
        "ErrorCode" => "",
        "TPMS" => ""
    ]
];

处理:

foreach ($master as $category => &$items) {  // allow modification of $master data with &
    foreach ($items as $k => &$v) {          // allow modification of $master data with &
        if (isset($json['Results'][0][$k]) && strlen($json['Results'][0][$k])) {  // only bother to process/display desired keys and non-empty values
            $new = $json['Results'][0][$k];
            if ($k == "DisplacementCC") {
                $v = "Engine Displacement 2: $new cc's";
            } elseif ($k == "DisplacementCI") {
                $v = "Engine Displacement 3: $new ci's";
            } elseif ($k == "DisplacementL") {
                $v = "Engine Displacement 1: " . round($new, 1) . " liters";
            } elseif ($k == "EngineKW") {
                $v = "Kilowatts: $new kw";
            } elseif ($k == "EngineManufacturer") {
                $v = "Engine Manufacturer: $new";
            } elseif ($k == "EngineModel") {
                $v = "Engine Model: $new";
            } elseif ($k == "FuelTypePrimary") {
                $v = "Primary Fuel Type: $new";
            } elseif ($k == "FuelTypeSecondary") {
                $v = "Secondary Fuel Type: $new";
            } elseif ($k == "EngineHP") {
                $v = "Horsepower: $new hp";
            } elseif ($k == "EngineCylinders") {
                $v = "Engine Size: $new cylinders";
            } else {
                $v = "$k: $new";
            }
        } else {
            unset($master[$category][$k]);  // remove unwanted element from master
        }
    }
}

unset($items, $v);  // just as a precaution to eliminate the referenced variables

echo "<div id=\"VIN\">{$json['Results'][0]['VIN']}</div>\n\n";
// now iterate the updated $master multi-dimensional array and only display the "good stuff"
foreach ($master as $category => $items) {
    if (!empty($items)) {  // only display categories & rows of data when the category holds 1 or more values
        echo "<div class=\"group\">$category -</ br>";
        foreach ($items as $v) {
            echo "<div class=\"row\">$v</div>";
        }
        echo "</div>";
    }
}

输出:

<div id="VIN">WAUBFAFL6FA058452</div>

<div class="group">General -</ br>
    <div class="row">Make: AUDI</div>
    <div class="row">ModelYear: 2015</div>
    <div class="row">Model: A4</div>
    <div class="row">BodyClass: Sedan/Saloon</div>
    <div class="row">Doors: 4</div>
    <div class="row">Series: Premium quattro</div>
    <div class="row">VehicleType: PASSENGER CAR</div>
</div>

<div class="group">Safety -</ br>
    <div class="row">AirBagLocCurtain: All Rows</div>
    <div class="row">AirBagLocFront: 1st Row (Driver & Passenger)</div>
    <div class="row">AirBagLocSide: 1st Row (Driver & Passenger)</div>
    <div class="row">SeatBeltsAll: Manual</div>
</div>

<div class="group">Engine -</ br>
    <div class="row">Engine Displacement 2: 1984 cc's</div>
    <div class="row">Engine Displacement 3: 121.071108283 ci's</div>
    <div class="row">Engine Displacement 1: 2 liters</div>
    <div class="row">Engine Size: 4 cylinders</div>
    <div class="row">Horsepower: 220 hp</div>
    <div class="row">Kilowatts: 164.0540 kw</div>
    <div class="row">Engine Manufacturer: Audi</div>
    <div class="row">Engine Model: Flex Fuel Capable engine</div>
    <div class="row">TransmissionStyle: Automatic</div>
    <div class="row">OtherEngineInfo: Fuel: Gas (50-St); Federal / California Emission Standard: BIN 5 / ULEV II; Emissions Certification Test Group: FVGAV02.0AUB / FVGAJ02.0AUF E85</div>
    <div class="row">Primary Fuel Type: Gasoline</div>
    <div class="row">Secondary Fuel Type: Ethanol (E85)</div>
</div>

<div class="group">Factory -</ br>
    <div class="row">Manufacturer: AUDI</div>
    <div class="row">ManufacturerId: 1149</div>
    <div class="row">PlantCity: Ingolstadt</div>
    <div class="row">PlantCountry: Germany</div>
</div>

<div class="group">Other -</ br>
    <div class="row">ErrorCode: 0 - VIN decoded clean. Check Digit (9th position) is correct</div>
    <div class="row">TPMS: Indirect</div>
</div>

*请注意,只有在您知道永远不会使用!empty()作为有效值的情况下,才可以使用isset()而不是strlen(),然后使用0empty()会将0误认为是“ falsy” /“ empty”值,并默默地要求从主数组中删除该元素。