2016-08-04 65 views
0

对不起noobie问题,我试图将一些json数据保存到我的数据库。问题是,我不知道如何获得任何“parent_names”。 “parent_name”总是与孩子“名字”相同。PHP - 从json保存对象键

价格data.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"; 
+1

如果父母名称和孩子的名称始终相同,那么问题是什么?只要使用两次孩子的名字。否则,您需要使用'key()'函数从数组中检索密钥。 –

+0

这是在哪个json的'父母名称:{}' - 'foreach($ array为$ parent_name => $ row)'也许? – ArtisticPhoenix

+0

问题是,我不知道每次parent_name将会是什么。 @GrzegorzGajda – Alex

回答

0

你需要从环路当前的阵列级别访问键,你可以做到这一点

foreach($array as $parent_name => $row) 

$row变量之前加上一个变量就认为这个像数组访问

array('key' => 'value') 

相同的交易。现在,因为您处于数组的“parent_name”级别,所以不需要将附加访问密钥放在那里。因此,对于这个

$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的密钥会给你一个未定义的索引警告,如果它是空的。