【问题标题】:How to convert a PHP array to a JSON array如何将 PHP 数组转换为 JSON 数组
【发布时间】:2014-11-25 12:57:17
【问题描述】:

我正在尝试将作为查询结果获得的 PHP 数组转换为 JSON 数组。但看起来它不起作用。如有任何帮助,我们将不胜感激。

        $stmt = $db->prepare("SELECT * FROM companies WHERE companyID = ?");

        if($stmt == "false"){
            die('Query error !'.$db->error);  
        }
        $stmt->bind_param('i', $companyID);
        $stmt->execute();
        $result = $stmt -> get_result();
        $companies = $result ->fetch_all(MYSQLI_BOTH);

        echo json_encode(array('companies' => $companies));

【问题讨论】:

  • 怎么不行?您当前代码的结果是什么?你希望它是什么样子?
  • 我希望有一个 JSON 数组,但没有 JSON 数组
  • But look like it does not work. 如果可能的话,请不要太具体
  • $result ->fetch_all 是否真的给了你一个 array 或者只是类似数组的东西?
  • echo json_encode(array('companies' => $companies)); 的结果是什么?

标签: php arrays json type-conversion


【解决方案1】:

看起来您遇到的是 JSON 本身。有一个existing, excellent answer here 可以解释这一点。总结就是 PHP 中带有字符串键的数组在 JSON 中是一个对象,因为数组只能有数字索引。

我希望这足以直接回答您的问题,并且我认为这将改变您对 PHP 和 JSON 之间关系的看法。

【讨论】:

    猜你喜欢
    • 2015-07-02
    • 2016-07-07
    • 2013-06-18
    • 1970-01-01
    • 1970-01-01
    • 2016-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多