更改 API 数据输出的布局 [英] Changing the Layout of API Data Output

查看:29
本文介绍了更改 API 数据输出的布局的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

数据存储为关联数组,包含类别及其对应的元素.例如,对于 VIN:WAUBFAFL6FA058452 类别之一是制造,其元素是奥迪.

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

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

我的下一个障碍是获取输出、类别及其元素,并在保持我上面定义的逻辑的同时组织/格式化它们.我只希望显示包含数据的类别.

我不确定如何定位单个类别来格式化它们.目前,输出按字母顺序显示.我想定义我自己的输出布局.

当前输出:

AirBagLocCurtain:所有行AirBagLocFront:第一排(驾驶员和乘客)AirBagLocSide:第一排(驾驶员和乘客)车身等级:轿车/轿车位移CC:1984位移CI:121.071108283位移L:1.984000等等....

如何更改此布局?我希望将输出布局更改为如下所示.

期望输出:

VIN: WAUBFAFL6FA058452一般的 -品牌:奥迪车型年份:2015型号:A4车身等级:轿车/轿车门:4系列: Premium quattro车辆类型:客车安全 -AirBagLocCurtain:所有行AirBagLocFront:第一排(驾驶员和乘客)AirBagLocSide:第一排(驾驶员和乘客)安全带全部:手动引擎 -位移CC:1984位移CI:121.071108283位移L:1.984000发动机缸数:4引擎HP:220发动机KW:164.0540发动机制造商:奥迪发动机型号:Flex Fuel Capable 发动机传输方式:自动OtherEngineInfo: 燃料: 气体 (50-St);联邦/加州排放标准:BIN 5/ULEV II;排放认证测试组:FVGAV02.0AUB/FVGAJ02.0AUF E85燃料类型主要:汽油燃料类型次要:乙醇 (E85)工厂 -制造商:奥迪制造商编号:1149植物城市:因戈尔施塔特工厂国家:德国其他 -错误代码:0 - VIN 解码干净.校验位(第 9 位)正确TPMS:间接

这是我的 html 代码,只有输入栏和提交按钮:

<头><title>VIN解码器API测试</title><style type="text/css">input,button {width: 200px;display: block;margin-left: auto;margin-right: auto;}按钮 {宽度:100 像素;背景颜色:深灰色;}</风格><身体><form action="processvin3.php" method="post"><input type="text" id="b12" placeholder="Enter VIN" name="b12" maxlength="100"/><br><button id="submit_btn">提交</button></表单><br><br></html>

还有我的 php 代码:

'json','数据' =>$vin]);$opts = ['http' =>['方法' =>'邮政','内容' =>$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){如果 (!empty($v)) {$results .= ($k).": ".($v).'<br/>';}}回声 $results;}别的 {echo '没有输入 Vin';}?>

非常感谢任何建议、提示或答案.非常感谢.

解决方案

我推荐使用主"数组来过滤和准备分类分组的数据.有关更多解释,请参阅内嵌注释:

代码:(演示)

你的主阵列:

$master = [一般"=>[制作" =>"",ModelYear" =>"",模型" =>"",BodyClass" =>"",门" =>"",系列" =>"",车辆类型" =>"],安全" =>[AirBagLocCurtain" =>"","AirBagLocFront" =>"",AirBagLocSide" =>"","SeatBeltsAll" =>"],引擎" =>[位移CC"=>"",位移CI"=>"",位移L"=>"",发动机气缸" =>"",EngineHP" =>"",发动机KW"=>"",发动机制造商"=>"",发动机型号" =>"",传输风格" =>"",其他引擎信息"=>"","FuelTypePrimary" =>"","FuelTypeSecondary" =>"],工厂" =>[制造商" =>"",制造商 ID" =>"",植物城" =>"",植物国家"=>"],其他"=>[错误代码" =>"",TPMS"=>"]];

处理:

foreach ($master as $category => &$ite​​ms) {//允许使用 & 修改 $master 数据foreach ($items as $k => &$v) {//允许使用 & 修改 $master 数据if (isset($json['Results'][0][$k]) && strlen($json['Results'][0][$k])) {//只需要处理/显示所需的键和非空值$new = $json['Results'][0][$k];if ($k == "DisplacementCC") {$v = "发动机排量 2: $new cc's";} elseif ($k == "DisplacementCI") {$v = "发动机排量 3:$new ci's";} elseif ($k == "DisplacementL") {$v = "发动机排量 1:" .round($new, 1) ."升";} elseif ($k == "EngineKW") {$v = "千瓦:$新千瓦";} elseif ($k == "EngineManufacturer") {$v = "发动机制造商:$new";} elseif ($k == "EngineModel") {$v = "发动机型号:$new";} elseif ($k == "FuelTypePrimary") {$v = "主要燃料类型:$new";} elseif ($k == "FuelTypeSecondary") {$v = "次要燃料类型:$new";} elseif ($k == "EngineHP") {$v = "马力:$new hp";} elseif ($k == "EngineCylinders") {$v = "发动机尺寸:$ 新气缸";} 别的 {$v = "$k: $new";}} 别的 {未设置($master[$category][$k]);//从 master 中删除不需要的元素}}}未设置($items,$v);//作为消除引用变量的预防措施echo "<div id=\"VIN\">{$json['Results'][0]['VIN']}</div>\n\n";//现在迭代更新后的 $master 多维数组,只显示好东西"foreach ($master as $category => $items) {if (!empty($items)) {//只显示类别 &类别包含 1 个或多个值时的数据行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">一般-</br><div class="row">制作:AUDI</div><div class="row">ModelYear: 2015</div><div class="row">型号:A4</div><div class="row">BodyClass:轿车/轿车</div><div class="row">门:4</div><div class="row">系列:Premium quattro</div><div class="row">VehicleType: PASSENGER CAR</div>

<div class="group">安全-</br><div class="row">AirBagLocCurtain:所有行</div><div class="row">AirBagLocFront:第一排(驾驶员和乘客)</div><div class="row">AirBagLocSide:第一排(驾驶员和乘客)</div><div class="row">SeatBeltsAll:手动</div>

<div class="group">引擎-</br><div class="row">Engine Displacement 2: 1984 cc</div><div class="row">Engine Displacement 3: 121.071108283 ci's</div><div class="row">发动机排量 1:2 升</div><div class="row">发动机尺寸:4缸</div><div class="row">马力:220 hp</div><div class="row">千瓦:164.0540 千瓦</div><div class="row">发动机制造商:奥迪</div><div class="row">引擎模型:Flex Fuel Capable引擎</div><div class="row">TransmissionStyle: Automatic</div><div class="row">OtherEngineInfo: Fuel: Gas (50-St);联邦/加州排放标准:BIN 5/ULEV II;排放认证测试组:FVGAV02.0AUB/FVGAJ02.0AUF E85</div><div class="row">主要燃料类型:汽油</div><div class="row">二次燃料类型:乙醇 (E85)</div>

<div class="group">工厂-</br><div class="row">制造商:AUDI</div><div class="row">ManufacturerId: 1149</div><div class="row">PlantCity: Ingolstadt</div><div class="row">PlantCountry: 德国</div>

<div class="group">其他-</br><div class="row">ErrorCode: 0 - VIN 解码干净.校验位(第 9 位)是否正确

<div class="row">TPMS:间接</div>

*注意,你可以使用 !empty() 而不是 isset() 然后 strlen() 只有当你知道你会永远不要将 0 作为有效值.empty() 会将 0 误认为falsy"/empty"值,并默默地调用从主数组中删除元素.

I am new to API integration and PHP. I recently integrated a VIN decoder into my app. Enter a vehicle's VIN into the input box, select submit, and all information regarding that vehicle from the API's database is presented.

The data is stored as an associative array, with categories and their corresponding elements. For example for VIN: WAUBFAFL6FA058452 one of the categories is Make and its element is Audi.

Some VIN's carry more data with them than others. I only wanted the categories with data to show up upon selecting submit. So with some help, I added this line of code:

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

My next hurdle is taking the output, the categories and their elements, and organizing/formatting them while keeping the logic I defined above. I only want the categories with data to show up.

I am not sure how to target single categories to format them. Currently, the output is presented in alphabetical order. I want to define my own output layout.

Current Output:

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....

How can I change this layout? I am looking to change the output layout to something like the following.

Desired Output:

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

Here is my html code, just the input bar and submit button:

<!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>

And my php code:

<?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';
    }




?>

Any suggestions, tips, or answers are greatly appreciated. Thanks so much.

解决方案

I recommend a "master" array to filter and prepare your categorically grouped data. See inline comments for more explanation:

Code: (Demo)

Your Master Array:

$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" => ""
    ]
];

Processing:

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>";
    }
}

Output:

<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>

*note, you can use !empty() rather than isset() then strlen() ONLY if you KNOW that you will never have 0 as a valid value. empty() will mistake 0 as a "falsy"/"empty" value and silently call for the element's removal from the master array.

这篇关于更改 API 数据输出的布局的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
PHP最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆