在PHP 7.0中编码多维数组不起作用(json_encode)

时间:2017-07-30 16:22:42

标签: php mysql json pdo encoding

我从mysql phpmyadmin(版本4.0)表获取JSON数据时遇到问题,我尝试过PDO和mysql_connect。

我的想法:mysql - > PHP - > echo json

与我的服务器的连接正常,SQL语句完美运行。我测试了它。但是JSON本身的" json_encode"(以及其他一些)是不可能的。 json数组未构建。

PhpMyAdmin中是否有必须注意的设置?

PDO:

      $query = $pdo->prepare('SELECT p.*, count(r.rate) AS rates, avg(r.rate) AS average from plugins p left join rate r on p.title = r.title group by p.title');
        $query->execute();
        $row = $query->fetchAll();
        // send the data encoded as JSON
        $json = json_encode($row, JSON_UNESCAPED_UNICODE);
echo $json;
       print_r($row);
        exit;

结果是:

Array ( [0] => Array ( [id] => 153 [0] => 153 [title] =>

我哪里错了?我将我的服务器更新为PHP 7.0 ,现在代码不起作用。在更新之前,所有工作都很完美,并且有一个很长的json数组(应该如何)

它应该如何

{{"id":"1","title":"ExmapleTitle"....},{"id":"2","title":"ExmapleTitle2"....}...} 

1 个答案:

答案 0 :(得分:2)

您必须调用execute()

    <?php

    $pdo = new PDO('mysql:host=xxxxx;dbname=xxxxx', 'xxxxxx', 'xxxxxx');

    $statement=$pdo->prepare("SELECT p.*, count(r.rate) AS rates, avg(r.rate) AS average from plugins p left join rate r on p.title = r.title group by p.title");

    $statement->execute(); // <<< --- You are missing this
    $data = $statement->fetchAll(PDO::FETCH_ASSOC);
    echo json_encode($data); //Echo: data ... voila