我已經使用下面的代碼從我的數據庫中提取數據並將其轉換爲數組。我的問題是echo json_encode函數不起作用,並且在運行此代碼時(沒有print_r函數),我留下了一個空白頁面。使用PHP將SQL查詢中的項目數組轉換爲JSON
$query = "SELECT * From table";
$resultarray = array();
if ($result = mysqli_query($connection, $query)) {
while ($row = mysqli_fetch_row($result)) {
$resultarray[] = $row;
}
print_r($resultarray); // This line shows that the array is works but the code below does not convert to JSON.
echo json_encode($resultarray);
}
我已經使用print_r函數來確保我已經在我的代碼中創建了一個數組。我在圈子裏走了幾個小時,我不明白我做錯了什麼。如果我使用print_r函數並查看頁面源,我會得到以下內容:
Array
(
[0] => Array
(
[0] => 5
[1] => Name 1
[2] => Description 1
[3] => Location 1
)
[1] => Array
(
[0] => 6
[1] => Name 2
[2] => Description 2
[3] => Location 2
)
[2] => Array
(
[0] => 45
[1] => Name 3
[2] => Description 3
[3] => Location 3
)
謝謝。
你有沒有想過你錯過了第一行關閉字符串的報價? – NoImaginationGuy
This [LINK](http://stackoverflow.com/a/19366999/4018240)可能對您有所幫助... –
謝謝@ManjeetBarnala問題解決了。我研究了這一點,並通過添加以下內容來解決它:mysqli_set_charset($ connection,「utf8」); – Brett