我是一個試圖在世界上找到我的方式的新手程序員。我已經掌握了我試圖解析出來的SQL語句來填充多個數據庫表的JSON數據。我想遍歷數組的每個維度並抽出它的特定部分來創建一個我可以傳遞給MySQL的INSERT語句。我不確定這是用一個JSON文件中的數據填充單獨表格的最佳方式,但這是我能想到的唯一方法。 MySQL表格是分開的,所以有一個人的表格,一個地址類型的表格,一個地址表格,一個電話表格,一個電子郵件表格等等。這是一個包含許多電話號碼,電子郵件地址等等。解析JSON在PHP中創建SQL插入語句
我已經能夠從外部URL解碼JSON。以下是使用print_r的代碼和輸出示例。
$json_string = 'http://....';
$jsondata = file_get_contents($json_string);
$data = json_decode($jsondata, TRUE);
1記錄樣品:
Array ([objects] => Array ([0] => Array ([first_name] => Anthony [last_name] => Perruzza [name] => Anthony Perruzza [elected_office] => City councillor [url] => http://www.toronto.ca/councillors/perruzza1.htm [gender] => [extra] => Array () [related] => Array ([boundary_url] => /boundaries/toronto-wards/york-west-8/ [representative_set_url] => /representative-sets/toronto-city-council/) [source_url] => http://www.toronto.ca/councillors/perruzza1.htm [offices] => Array ([0] => Array ([tel] => 416-338-5335)) [representative_set_name] => Toronto City Council [party_name] => [district_name] => York West (8) [email] => [email protected] [personal_url] => [photo_url] =>)) [meta] => Array ([next] => /representatives/?limit=1&offset=1 [total_count] => 1059 [previous] => [limit] => 1 [offset] => 0))
JSON代碼示例:
{"objects": [
{"first_name": "Keith",
"last_name": "Ashfield",
"name": "Keith Ashfield",
"elected_office": "MP",
"url": "http://www.parl.gc.ca/MembersOfParliament/ProfileMP.aspx?Key=170143&Language=E",
"gender": "",
"extra": {},
"related": {
"boundary_url": "/boundaries/federal-electoral-districts/13003/",
"representative_set_url": "/representative-sets/house-of-commons/"
},
"source_url": "http://www.parl.gc.ca/MembersOfParliament/MainMPsCompleteList.aspx?TimePeriod=Current&Language=E",
"offices": [
{ "type": "legislature",
"fax": "613-996-9955",
"postal": "House of Commons\nOttawa, Ontario\nK1A 0A6",
"tel": "613-992-1067"
},
{ "type": "constituency",
"fax": "506-452-4076",
"postal": "23 Alison Blvd (Main Office)\nFredericton, New Brunswick\nE3C 2N5",
"tel": "506-452-4110"
}
],
"representative_set_name": "House of Commons",
"party_name": "Conservative",
"district_name": "Fredericton",
"email": "[email protected]",
"personal_url": "",
"photo_url": "http://www.parl.gc.ca/MembersOfParliament/Images/OfficialMPPhotos/41/AshfieldKeith_CPC.jpg"
}
],
"meta": {
"next": "/representatives/house-of-commons/?limit=1&offset=1",
"total_count": 307,
"previous": null,
"limit": 1,
"offset": 0
}
}
,你可以提供任何幫助將不勝感激。在過去的幾天裏,我一直在努力弄清楚自己的頭髮。
我試過自定義代碼,如下所示,使其工作,但我一直沒有能夠擊中甜蜜點。請不要,這段代碼不會引用我的數據或變量。我刪除了不適合我的東西。我只是包括它給你一個想法,我已經嘗試過。
foreach ($data as $item) {
echo $item->{'first_name'} . "<br/>";
echo $item->{'last_name'};
}
如果你能指出我能夠解析出數組的任何級別的數據的方向,將不勝感激。
最佳,
小號
我認爲json代碼的代表性樣本也會有用,如果您可以發佈該代碼? – vascowhite 2012-03-18 19:16:14
閱讀http://www.php.net/manual/en/language.types.array.php – Rob 2012-03-18 19:06:40
感謝您的回覆。剛剛發佈了上面的JSON示例。我也閱讀上面提供的手動鏈接,並通過我正在閱讀的內容嘗試其他幾個。 – RawAnimal 2012-03-18 20:41:50