2016-08-04 2 views
0

noobie 질문에 대한 사과, 내 데이터베이스에 일부 json 데이터를 저장하려고합니다. 문제는 "parent_names"를 얻는 방법을 모르겠다는 것입니다. "parent_name"은 항상 하위 "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

parent_name과 하위 이름이 항상 같은 경우 문제가 무엇입니까? 아이의 이름을 두 번 사용하십시오. 그렇지 않으면'key()'함수를 사용하여 배열에서 키를 검색해야합니다. –

+0

여기서 json'parent_name : {}'- foreach ($ array as $ parent_name => $ row)'아마도? – ArtisticPhoenix

+0

문제는 매번 parent_name이 어떻게 될지 모르기 때문입니다. @ GrzegorzGajda – Alex

답변

0

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

$row 변수 앞에 변수를 추가하면 배열 액세스로 생각됩니다

array('key' => 'value') 

같은 거래가 있습니다. 이제 배열의 "parent_name"레벨에 있기 때문에 거기에 추가 액세스 키를 넣을 필요가 없습니다. 당신이 그 다음 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 
     } 

의이 부분에서 작업 할 것이기 때문에이

$row["parent_name"]["7_days"]["volume"] 

당신은 단지

$row["7_days"]["volume"] 

을 수행 할 수 있습니다 그래서 당신은 당신의 JSON에 외부 배열 래퍼를 가지고 있기 때문에 [{ .. }] 대괄호. $array[0] 또는 $array = reset($array)을해야 할 수도 있습니다. 배열이 비어있는 경우 PHP에서 경고 메시지가 표시되지 않으므로 재설정이 더 좋습니다 (해당되는 경우). 본질적으로 0 키에 액세스하려고하면 비어있는 경우 정의되지 않은 색인 경고가 표시됩니다.