抱歉这个菜鸟问题,我正在尝试将一些 json 数据保存到我的数据库中。问题是,我不知道如何获取任何“parent_names”。 “parent_name”始终与子“name”相同。
价格数据.json
[
{
"Flag": {
"name": "Flag",
"safe_price": "118.31",
"safe_net_price": "110.60",
"total_volume": 3148,
"7_days": {
"median_price": "118.31",
"lowest_price": "100.00",
"highest_price": "132.25",
"volume": 94
}
},
"Pole": {
"name": "Pole",
"safe_price": "81.21",
"safe_net_price": "70.62",
"total_volume": 1,
"7_days": {
"volume": 0
}
},
"Net": {
"name": "Net",
"safe_price": "0.89",
"safe_net_price": "0.84",
"total_volume": 763,
"7_days": {
"median_price": "0.89",
"lowest_price": "0.65",
"highest_price": "1.08",
"volume": 30
}
}
}
]
php
$filename = "price-data.json";
$data = file_get_contents($filename);
$array = json_decode($data, true);
foreach($array as $row)
{
$sql = "INSERT INTO table_all_prices(parent_name, name, safe_price, safe_net_price, total_volume, median_price, lowest_price, highest_price, volume) VALUES (
'".$row["parent_name"]."',
'".$row["parent_name"]["name"]."',
'".$row["parent_name"]["safe_price"]."',
'".$row["parent_name"]["safe_net_price"]."',
'".$row["parent_name"]["total_volume"]."',
'".$row["parent_name"]["7_days"]["median_price"]."',
'".$row["parent_name"]["7_days"]["lowest_price"]."',
'".$row["parent_name"]["7_days"]["highest_price"]."',
'".$row["parent_name"]["7_days"]["volume"]."'
)";
}
echo "All Prices inserted to database";
最佳答案
您需要从循环中的当前数组级别访问 key ,可以通过
foreach($array as $parent_name => $row)
在 $row
变量之前添加一个变量,就像数组访问一样
array( 'key' => 'value' )
同样的交易。现在,因为您位于数组的“parent_name”级别,所以不需要将额外的访问 key 放在那里。所以对于这个
$row["parent_name"]["7_days"]["volume"]
你可以这样做
$row["7_days"]["volume"]
因为您将处理 json 的这一部分
"name": "Net",
"safe_price": "0.89",
"safe_net_price": "0.84",
"total_volume": 763,
"7_days": {
"median_price": "0.89",
"lowest_price": "0.65",
"highest_price": "1.08",
"volume": 30
}
然后因为你的 json [{ .. }]
这些方括号上有一个外部数组包装器。您可能需要执行 $array[0]
或 $array = reset($array)
。重置可能更好(如果事实确实如此),因为如果数组为空,您将避免来自 PHP 的一些警告消息。本质上,尝试访问 0
键(如果该键为空)将会给您一个 undefined index 警告。
关于PHP - 从 json 保存对象键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38777116/