使用 If 语句更改数组输出 [英] Changing Array Output with If Statements
问题描述
我是 API 集成和 PHP 的新手.我最近在我的应用程序中集成了一个 VIN 解码器.在输入框中输入车辆的 VIN,选择提交,然后会显示 API 数据库中有关该车辆的所有信息.
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.
数据存储为关联数组,包含类别及其对应的元素.例如,对于 VIN:WAUBFAFL6FA058452,其中一个类别是 Make,其元素是 Audi.
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.
某些 VIN 携带的数据比其他 VIN 多.我只希望在选择提交时显示带有数据的类别.所以在一些帮助下,我添加了这行代码:
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 />';
}
这是输出的样子:
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 代码中看到这种尝试.关于如何编辑类别名称的任何想法?
What I want to do next is edit the category name. For example: change ModelYear to Year, TransmissionStyle to Transmission Type, EngineHP to Horsepower, and so on. I tried adding a simple IF Statement with $k as the variable; however, this did not work. You will see this attempt in my PHP code below. Any ideas on how to edit category names?
这是我的html,它是一个简单的输入栏和提交按钮:
Here is my html, it is a simple 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>
还有我的 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';
}
?>
非常感谢您提供的任何帮助.
Thanks so much for any help you can provide.
推荐答案
我推荐查找数组而不是一组条件.
I recommend a lookup array versus a battery of conditionals.
代码:(演示)
$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()
调用).
Now that I see your new project requirements, an if/elseif
block is better suited (because of the conditional round()
call).
代码:(演示)
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>";
这篇关于使用 If 语句更改数组输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!