[英]How to convert json to php array and only pull specific value from json
如何將JSON / PHP
數組插入MYSQL
這是JSON
值:
{"siteCurrentPowerFlow":
{
"updateRefreshRate":3,
"unit":"kW",
"connections":
[
{"from":"PV","to":"Load"},
{"from":"GRID","to":"Load"}
],
"GRID":{"status":"Active","currentPower":65.63},
"LOAD":{"status":"Active","currentPower":82.37},
"PV":{"status":"Active","currentPower":16.74}
}
}
這是我得到的PHP
數組:
Array ( [siteCurrentPowerFlow] => Array ( [updateRefreshRate] => 3 [unit] => kW [connections] => Array ( [0] => Array ( [from] => PV [to] => Load ) [1] => Array ( [from] => GRID [to] => Load ) ) [GRID] => Array ( [status] => Active [currentPower] => 51.68 ) [LOAD] => Array ( [status] => Active [currentPower] => 79.43 ) [PV] => Array ( [status] => Active [currentPower] => 27.75 ) ) )
如何從PHP
插入到mysql
?
我假設我需要使用foreach
循環,但我不知道如何格式化foreach
循環
$arrContextOptions = [
'ssl' => [
'verify_peer' => false,
'verify_peer_name' => false
]
];
$data = file_get_contents($url, false, stream_context_create($arrContextOptions));
$decoded_data = json_decode($data, true);
print_r($decoded_data);
解碼你的json字符串
$data = (array) json_decode('put your json data here');
我需要插入“GRID”:{“status”:“Active”,“currentPower”:65.63} MYSQL:id,currentPower(mysql中的2列)| 當我這樣做:$ decoding_data = json_decode($ urld,true); $ data = $ decoding_data [“siteCurrentPowerFlow”] [“GRID”]; 的print_r($數據); 我得到了正確的數組:Array([status] => Active [currentPower] => 65.63)如何只將這個插入到mysql
$decoded_data = json_decode($json_data,true);
$id = ... // set your id
$current_power = $decoded_data['siteCurrentPowerFlow']['GRID']['currentPower']; // fetch data from array
// connect to your db
$mysqli = new mysqli(...); // put your connection config here
if ($mysqli->connect_errno) {
die("connection error: " . $mysqli->connect_error);
}
//Prepared statement
$sql = "INSERT INTO your_table (id, current_power) VALUES (?,?)"; // change columns to your table schema
$statement = $mysqli->prepare($sql);
$statement->bind_param('id', $id, $current_power); //type definition i for integer (id column) , d for double (current_power column). Bind your variables
$statement->execute();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.