[英]Parsing JSON with PHP multiple arrays to MYSQL table
這里的stackoverflow新手。 我一直在閱讀類似的文章,試圖將我想要的代碼組合在一起。 對PHP和JSON來說還算是新手,所以去吧。
我試圖拆分一些JSON數據,最終目的是將數據存儲為MySQL表中的兩個單獨的列。 JSON數據如下所示-
{
"request": {
"command": "series",
"series_id": "PET.RBRTE.A"
},
"series": [{
"series_id": "PET.RBRTE.A",
"name": "Europe Brent Spot Price FOB, Annual",
"units": "Dollars per Barrel",
"f": "A",
"unitsshort": "$\/bbl",
"description": "Europe Brent Spot Price FOB",
"copyright": "Thomson-Reuters",
"source": "Thomson-Reuters",
"start": "1987",
"end": "2015",
"updated": "2016-05-16T16:56:05-0400",
"data": [
["2015", 52.32],
["2014", 98.97],
["2013", 108.56],
...
]
}]
可以通過URL直接獲得此JSON數據,因此我正在使用$json = file_get_contents
和$array = json_decode($json, true)
將數據最初放入數組。
轉儲數組var_dump($array)
顯示如下:
Array
(
[request] => Array
(
[command] => series
[series_id] => PET.RBRTE.A
)
[series] => Array
(
[0] => Array
(
[series_id] => PET.RBRTE.A
[name] => Europe Brent Spot Price FOB, Annual
[units] => Dollars per Barrel
[f] => A
[unitsshort] => $/bbl
[description] => Europe Brent Spot Price FOB
[copyright] => Thomson-Reuters
[source] => Thomson-Reuters
[start] => 1987
[end] => 2015
[updated] => 2016-05-16T16:56:05-0400
[data] => Array
(
[0] => Array
(
[0] => 2015
[1] => 52.32
)
[1] => Array
(
[0] => 2014
[1] => 98.97
)
[2] => Array
(
[0] => 2013
[1] => 108.56
)
[3] ...
)
)
)
到目前為止一切都很好。 然后,我想使用data
數組系列獲取子數組數據,在此特定的JSON數據集中有29個。 每個子數組中的[0]是日期(年),[1]是與該年關聯的值。
我最能得到的數據是下面的代碼-
$array_data = implode(",", $array['series'][0]['data'][0]);
當使用echo '<pre>'; print_r(($array_data)); echo '</pre>';
echo '<pre>'; print_r(($array_data)); echo '</pre>';
給我2015,52.32
,但是我想要得到的是每個子數組的結果作為它們自己的變量,然后我可以使用它們插入到MySQL中,例如-
2015,52.32
2014,98.97
2013,108.56
...,...
然后,我將使用插入語句將第一個值添加到datetype列中,然后將第二個值添加到小數列中。
我覺得我將在很長的路要走,所以如果有人對如何改進它以獲得最終結果有任何建議,我將不勝感激。 謝謝您的幫助。
使用for
循環:
$dataArray = $array['series'][0]['data'];
for ($i = 0; $i < count($dataArray); $i++) {
$implosion = $dataArray[$i]);
}
如果您想要字典:
$dataArray = $array['series'][0]['data'];
$dict = [];
for ($i = 0; $i < count($dataArray); $i++) {
$dict[dataArray[$i][0]] = $dataArray[$i][1];
}
給予:
Array
(
[2015] => 52.32
...
)
編輯對於單獨的循環:
$dataArray = $array['series'][0]['data'];
$dates = [];
$values = [];
for ($i = 0; $i < count($dataArray); $i++) {
array_push($dates, $dataArray[$i][0]);
array_push($values, $dataArray[$i][1]);
}
$dateImplosion = implode(", ", $dates);
echo $dateImplosion;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.