2016-08-04 74 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的密鑰會給你一個未定義的索引警告,如果它是空的。