如何使用 PHP json 将单个对象编码为 json 对象数组

How to json encode a single object as a json objects array using PHP

对于两个对象:

    {"publications":[{"nom":"toto","id":"2029","userid":"22","publication":"bla bla bla","time":"2017-02-20 00:00:00","avatar":{}},{"nom":"xxxx","id":"2027","userid":"31","publication":"kjdsfkuds","time":"2017-02-20 00:00:00","avatar":{}}]}

对于一个对象:

    {"publications":{"nom":"xxxx","id":"2027","userid":"31","publication":"kjdsfkuds","time":"2017-02-20 00:00:00","avatar":{}}}

我希望始终有一个 json 数组作为一个 return,无论对象的数量如何。

PHP代码:

    $result = $conn->query($sql);
    $json = new SimpleXMLElement('<xml/>');

  if ($result->num_rows > 0) {
   while($row = $result->fetch_assoc()) {
    $mydata = $json->addChild('publications');
    $mydata->addChild('nom',$row['nom']);
    $mydata->addChild('id',$row['id']);
    $mydata->addChild('userid',$row['userid']);
    /*echo(utf8_encode($row['publication']));*/
    $mydata->addChild('publication',utf8_encode($row['publication']));
    $mydata->addChild('time',$row['time']);
    $mydata->addChild('avatar',$row['avatar']);

     }
     echo( json_encode ($json));
    } else {
      echo "0";
    }

这是 SimpleXML 的一个特殊行为。

如果您在 xml 中有一个 child - 您将在 json 中有一个 object,如果您有多个 child - 您将获得 object 的数组。因此,我建议您使用简单的数组而不是 xml-approach:

重写代码
$result = $conn->query($sql);
$json = [];  // just array

if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        // add new item
        $json[] = $row;   

        // or more specifically
        $json[] = [
            'nom' => $row['nom'],
            'id' => $row['id'],
            // more fields that you need
        ];   
    }
}
echo json_encode(['publications' => $json]);

好吧,您没有将 XML 用于其他用途,而是将其转换为 JSON,因此不需要 XML。使用数组

$result = $conn->query($sql);
$json = ['publications' => []];

if($result->num_rows > 0)
{
    while($row = $result->fetch_assoc())
    {
        $json['publications'][] = [
            'nom' => $row['nom'],
            'id' => $row['id'],
            'userid' => $row['userid'],
            'publication' => $row['publication'],
            'time' => $row['time'],
            'avatar' => $row['avatar']
        ];
    }
    echo json_encode($json);
}
else
{
    echo "0";
}