【问题标题】:Changing Array Output with If Statements使用 If 语句更改数组输出
【发布时间】:2018-08-17 19:35:34
【问题描述】:

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

?>

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

【问题讨论】:

标签: php html arrays api


【解决方案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>";

【讨论】:

  • 感谢您的回复。为什么你更喜欢查找而不是条件?
  • 它更易于阅读和维护...但是,既然我看到了您对该项目的新问题(特别是round()),您最好使用if-elseif 块或@ 987654330@ 块。我会回答你的新问题
  • @mugelloblue 考虑到您的新问题的详细信息,我已经更新了我的答案。如果您满意,请接受我的回答,以便此问题被视为已解决。 (您所有的问题最终都应该得到一个绿色勾选的答案,以便:1. 未来的读者可以自信地从最佳答案中学习 2. 志愿者为您提供支持而获得奖励 3. 以便系统知道这个问题已解决。