【问题标题】:Stripping JSON encoding of PHP array剥离 PHP 数组的 JSON 编码
【发布时间】:2017-06-04 19:58:55
【问题描述】:

我有一个使用 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"]

提前谢谢你。

【问题讨论】:

    标签: javascript php mysql json


    【解决方案1】:

    如果您的代码中不再需要对象数组 ($ws),您可以将代码简化为:

    $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();
    

    【讨论】:

    • 谢谢!显然我把事情复杂化了:)
    • 如果答案有帮助 - 请随时接受它,作为您之前问题的答案。它对您和回答者都有帮助)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-12
    • 2016-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-21
    相关资源
    最近更新 更多