2017-06-04 67 views
0

我使用PHP完成了MySQL查詢,結果以數組形式呈現。剝離PHP陣列的JSON編碼

$stmt = $mysqli->prepare("SELECT word FROM words ORDER BY RAND() LIMIT 5"); 
    $stmt->bind_result($words); 

$stmt->execute(); 
$result = array(); 

while ($stmt->fetch()) { 
    $w = new StdClass(); 
    $w->word = $words; 
    array_push($result, $w); 
} 
$stmt->close(); 

然後,我使用JSON傳遞數組的JavaScript:

'words' : <?php echo json_encode($result); ?>, 

但輸出是:

[{"word":"Watermelon"},{"word":"Orange"},{"word":"Melon"},{"word":"Cucumber"},{"word":"Apple"}] 

是否有任何方式爲 「條」 之「字「並讓它看起來像那樣?

["Watermelon", "Orange", "Melon", "Cucumber", "Apple"] 

在此先感謝您。

回答

2

如果你不需要的對象($w S)的陣列進一步在你的代碼,您可以簡化代碼:

$stmt = $mysqli->prepare("SELECT word FROM words ORDER BY RAND() LIMIT 5"); 
$stmt->bind_result($words); 

$stmt->execute(); 
$result = array(); 

while ($stmt->fetch()) { 
    array_push($result, $words); 
} 
$stmt->close(); 
+0

謝謝!顯然我過於複雜的東西:) –

+0

如果答案有幫助 - 隨時接受它,作爲您以前的問題的答案。它可以幫助你和回答者) –