我使用PHP完成了MySQL查询,结果显示为数组。
$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"]
提前谢谢。
答案 0 :(得分:2)
如果您的代码中不需要对象数组($w
),则可以将代码简化为:
$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();