使用If语句更改数组输出 [英] Changing Array Output with If Statements

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

问题描述

我是API集成和PHP的新手.我最近将VIN解码器集成到了我的应用中.在输入框中输入车辆的VIN,然后选择Submit(提交),并显示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,等等.我尝试添加$ k作为变量的简单IF语句;但是,这没有用.您将在下面的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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆