亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用 PHP 將氣象站 API URL 轉換為 csv

使用 PHP 將氣象站 API URL 轉換為 csv

PHP
千巷貓影 2023-08-19 10:34:39
我正在嘗試使用我的氣象站的 API,據我所知是 JSON 格式,并轉換為 csv 文件。API返回:[{"macAddress":"xx:xx:xx:xx:xx:xx","lastData":{"dateutc":1595258880000,"tempinf":74.3,"humidityin":44,"baromrelin":29.929,"baromabsin":29.235,"tempf":85.5,"battout":1,"humidity":62,"winddir":167,"windspeedmph":0.2,"windgustmph":1.1,"maxdailygust":9.2,"hourlyrainin":0,"eventrainin":0,"dailyrainin":0,"weeklyrainin":0,"monthlyrainin":0.571,"totalrainin":1.823,"solarradiation":832.38,"uv":8,"feelsLike":90.84,"dewPoint":70.96,"feelsLikein":73.5,"dewPointin":51,"tz":"America/Chicago","date":"2020-07-20T15:28:00.000Z"},"info":{"name":"MyWeatherStation","coords":{"coords":{"lon":134.65635809999999,"lat":32.6587316},"address":"100Park Lane, Yourtown, TN 77777,USA","location":"Yourtown","elevation":146.7066497802734,"geo":{"type":"Point","coordinates":[134.65635809999999,32.6587316]}}}}]通過 wtools.io/convert-json-to-php-array 格式化的代碼網頁代碼:<?php // Read JSON file $readjson = file_get_contents("https://weather_api") ;//Decode JSON $data = json_decode($readjson, true);//Print data print_r($data); echo "<br/><br/> Weather Stats are: <br/>";//function to convert to csv file //Give our CSV file a name. $csvFileName = 'example.txt';   //Open file pointer. $fp = fopen($csvFileName, 'w');   //Loop through the associative array. foreach($data as $row){    //Write the row to the CSV file.      fputcsv($fp, $row); }//Finally, close the file pointer. fclose($fp);文件已創建,但我沒有獲得正確的數據。評論/想法將不勝感激。xx:xx:xx:xx:xx:xx,數組,數組
查看完整描述

1 回答

?
手掌心

TA貢獻1942條經驗 獲得超3個贊

您需要展平數組(意味著將每個值放入第一個維度)。


應用于您的示例,您需要這樣的東西:

$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($data));

$csvArray = [];

foreach($iterator as $value) {

? ? $csvArray[] = $value;

}


fputcsv($fp, $csvArray);

工作示例。

編輯 - 更具可讀性的數組扁平化器

function getFlatArray($data, $keyPrefix = '') {

? ? $result = [];

? ??

? ? foreach ($data as $key => $value) {

? ? ? ? $newKey = $keyPrefix . $key;

? ? ? ??

? ? ? ? if (!is_array($value)) {

? ? ? ? ? ? $result[$newKey] = $value;

? ? ? ? } else {

? ? ? ? ? ? $result += getFlatArray($value, $newKey . '-');

? ? ? ? }

? ? }

? ??

? ? return $result;

}


$csvArray = getFlatArray(array_pop($data));


fputcsv($fp, array_keys($csvArray)); // add keys to first line

fputcsv($fp, $csvArray);

工作示例



查看完整回答
反對 回復 2023-08-19
  • 1 回答
  • 0 關注
  • 97 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號