簡體   English   中英

使用 If 語句更改數組輸出

[英]Changing Array Output with If Statements

我是 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,等等。 我嘗試添加一個簡單的 IF 語句,其中 $k 作為變量; 然而,這並沒有奏效。 您將在下面的 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';
  }

?>

非常感謝您提供的任何幫助。

我推薦一個查找數組而不是一組條件。

代碼:(演示

$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);

現在我看到了您的新項目要求,更適合使用if/elseif塊(因為有條件的round()調用)。

代碼:(演示

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM