如何将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 ) ) )
如何将其从mysql
插入PHP
?
我假设我需要使用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);
答案 0 :(得分:0)
解码您的json字符串
$data = (array) json_decode('put your json data here');
答案 1 :(得分:0)
我需要插入“ GRID”:{“状态”:“活动”,“ currentPower”:65.63} MYSQL:id,currentPower(mysql中为2列)|当我这样做时:$ decoded_data = json_decode($ urld,true); $ data = $ decoded_data [“ siteCurrentPowerFlow”] [“ GRID”]; print_r($ data);我得到正确的数组: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();