数组中的限制和排序值

时间:2018-03-11 02:04:20

标签: php arrays sorting limiting

使用来自NHTSA的API的一些代码,我自己和来自这个网站的想法,将它包装成一个函数,它工作得很好但不能在我的实时服务器上运行。

在实时服务器上,它给出了一个错误,我最终使用我的实时服务器的PHP版本不支持的数组快捷方式解决了代码:

解析错误:语法错误,意外情况' [',期待')'在/home/pchome/public_html/verify/functions/sitefunctions.php第9行

就是这一行:

$postdata = http_build_query(["data" => $VINS, "format" => "JSON"]);

更改为此工作,并以相同的方式更改了其他几个地方的类似代码:

$postdata = http_build_query(array("data" => $VINS, "format" => "JSON"));

偶尔(但并非总是)我可能希望将多个VIN作为分号分隔列表传递给它。这种格式不可更改,那么提供此功能需要什么? (样本VIN:3GNDA13D76S000000; 5XYKT3A12CG000000

// Uses NHTSA API to decode VIN(s)
function decodeVINS($VINS) {
    if ($VINS) :
        $return = "";
        $postdata = http_build_query(array("data" => $VINS, "format" => "JSON"));
        $stream_options = array(
                            'http' => array(
                                'header' => "Content-Type: application/x-www-form-urlencoded\r\n".
                                            "Content-Length: ".strlen($postdata)."\r\n",
                                'method' => "POST",
                                'content' => $postdata
                            )
                        );
        $context = stream_context_create($stream_options);
        $apiURL = "https://vpic.nhtsa.dot.gov/api/vehicles/DecodeVINValuesBatch/";

        $fp = @fopen($apiURL, 'rb', FALSE, $context);
        $results = array_column(json_decode(@stream_get_contents($fp),TRUE), '0');
        $results = $results[0];

        $output = "<blockquote>\n";
        $output .= "<div><strong>VIN: {$results['VIN']}</strong></div>\n";
        $output .= "<div><strong>ErrorCode: {$results['ErrorCode']}</strong></div>\n";

        if ($results['AdditionalErrorText']) :
            $output .= "<div><strong>AdditionalErrorText: {$results['AdditionalErrorText']}</strong></div>\n";
        endif;

        foreach ($results as $key => $val) :
            if ($val && $key != "VIN" && $key != "ErrorCode" && $key != "AdditionalErrorText") :
                $output .= "<div>$key: $val</div>";
            endif;
        endforeach;

        $output .= "</blockquote>\n\n";
    else :
        $output = "Enter VINs above separated by line breaks";
    endif;

    return $output;
}

。 。 。它正在输出这样的东西:

VIN: JB7FJ43S5KJ000911
ErrorCode: 0 - VIN decoded clean. Check Digit (9th position) is correct
BodyClass: Sport Utility Vehicle (SUV)/Multi Purpose Vehicle (MPV)
DisplacementCC: 3000
DisplacementCI: 183.0712322841
DisplacementL: 3
DriveType: 4WD/4-Wheel Drive/4x4
EngineConfiguration: V-Shaped
EngineCylinders: 6
FuelTypePrimary: Gasoline
GVWR: Class 1C: 4,001 - 5,000 lb (1,814 - 2,268 kg)
Make: DODGE
Manufacturer: MITSUBISHI MOTORS CORPORATION (MMC)
ManufacturerId: 1052
Model: Raider
ModelYear: 1989
PlantCity: Nagoya
PlantCompanyName: Nagoya #3
PlantCountry: Japan
VehicleType: TRUCK 

2 个答案:

答案 0 :(得分:1)

在我看来,使用JSON而不是CSV会更加容易/直接/稳定。

我在自定义函数调用中添加了一个参数($fields),它将指示如何隔离和排序数据。

我还修改了第一个参数($VINs),将其作为数组而不是以分号分隔的字符串传递。我希望简化您的处理 - 如果不是,欢迎您回退到原始字符串格式并删除我的implode(";",$VINs)电话。

代码:(Demo

function searchByVINs ($VINs,$fields) {
    // test multi-VIN batching via textarea at bottom of https://vpic.nhtsa.dot.gov/api/
    $stream_options_content = http_build_query(["data" => implode(";", $VINS), "format" => "JSON"]);
    $stream_options = [
        'http' => [
            'header' => "Content-Type: application/x-www-form-urlencoded\r\n".
                        "Content-Length: ".strlen($postdata)."\r\n",
            'method' => "POST",
            'content' => $postdata
        ]
    ];
    $context = stream_context_create($stream_options);
    $apiURL = "https://vpic.nhtsa.dot.gov/api/vehicles/DecodeVINValuesBatch/";

    if (!$fp = @fopen($apiURL, "rb", FALSE, $context)) {
        return ["success" => false, "response" => "Unable to open stream"];
    }

    if (!$response = stream_get_contents($fp),true)) {
        return ["success" => false, "response" => "Unable to receive streamed data"];
    }

    if(($data = @json_decode($response,true)) === null && json_last_error()!==JSON_ERROR_NONE){
        return ["success" => false, "response" => "Unable to parse streamed data"];
    }

    if (!isset($data["Message"]) || $data["Message"] != "Results returned successfully") {
        return ["success" => false, "response" => "Received unsuccessful dataset"];
    }

    $return = [];
    $keys = array_flip($fields);
    foreach ($data["Results"] as $dataset) {
        $isolated = array_intersect_key($dataset,$keys);  // only retain the elements with keys that match $fields values
        $sorted = array_replace($keys,$isolated);  // order the dataset by order of elements in $fields
        $return[] = $sorted;
    }

    return ["success" => true, "response" => $return];
}


$VINs = ["3GNDA13D76S000000", "5XYKT3A12CG000000"];
$fields = ["VIN", "ModelYear", "Make", "FuelTypePrimary", "DriveType", "BodyClass"];
$response = searchByVINs($VINs,$fields);

if (!$response["success"]) {
    echo "Oops, the api call failed. {$response["response"]}";
} else {
    foreach ($response["response"] as $item){
        echo "<div>";
        foreach ($item as $key => $value) {
            echo "<div>$key: $value</div>";
        }
        echo "</div>";
    }
}

输出(来自模拟演示)

<div>
    <div>VIN: 3GNDA13D76S000000</div>
    <div>ModelYear: 2006</div>
    <div>Make: CHEVROLET</div>
    <div>FuelTypePrimary: Gasoline</div>
    <div>DriveType: </div>
    <div>BodyClass: Wagon</div>
</div>
<div>
    <div>VIN: 5XYKT3A12CG000000</div>
    <div>ModelYear: 2012</div>
    <div>Make: KIA</div>
    <div>FuelTypePrimary: Gasoline</div>
    <div>DriveType: 4x2</div>
    <div>BodyClass: Wagon</div>
</div>

答案 1 :(得分:0)

现在所有工作都是最终版本!根据需要,仅显示具有值的行,并且可以在一个提交中处理多个VIN。该函数从一个简单的表单中调用,该表单具有用于输入VIN的textarea以及一个Submit按钮。

// Uses NHTSA API to decode VIN(s)
function decodeVINS($VINS) {
    // sample VINs 3GNDA13D76S000000;5XYKT3A12CG000000
    if ($VINS) :
        $postdata = http_build_query(array("data" => $VINS, "format" => "JSON"));
        $stream_options = array(
                            'http' => array(
                                'header' => "Content-Type: application/x-www-form-urlencoded\r\n".
                                            "Content-Length: ".strlen($postdata)."\r\n",
                                'method' => "POST",
                                'content' => $postdata
                            )
                        );
        $context = stream_context_create($stream_options);
        $apiURL = "https://vpic.nhtsa.dot.gov/api/vehicles/DecodeVINValuesBatch/";

        $fp = @fopen($apiURL, 'rb', FALSE, $context);
        $returnValue = json_decode(@stream_get_contents($fp),TRUE);
        if(!isset($returnValue['Results'])):
            echo "Invalid return data or no return data. Exiting";
            return FALSE;
        endif;
        $results = $returnValue['Results'];

        if(!is_array($results)):
            $results = array($results);
        endif;

        $output = '';
        foreach($results as $result):
            $output .= "<blockquote>\n";
            $output .= "<div><strong>VIN: {$result['VIN']}</strong></div>\n";
            $output .= "<div><strong>ErrorCode: {$result['ErrorCode']}</strong></div>\n";

            if ($result['AdditionalErrorText']) :
                $output .= "<div><strong>AdditionalErrorText: {$result['AdditionalErrorText']}</strong></div>\n";
            endif;

            foreach ($result as $key => $val) :
                if ($val && $key != "VIN" && $key != "ErrorCode" && $key != "AdditionalErrorText") :
                    $output .= "<div>$key: $val</div>";
                endif;
            endforeach;
            $output .= "</blockquote>\n\n";
        endforeach;
    else :
        $output = "Enter VINs above separated by line breaks";
    endif;

    return $output;
}