【问题标题】:How to json encode a single object as a json objects array using PHP如何使用 PHP 将单个对象 json 编码为 json 对象数组
【发布时间】:2017-04-27 20:21:48
【问题描述】:

对于两个对象:

    {"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 数组作为返回。

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 并使用普通数组。

标签: php arrays json object encode


【解决方案1】:

好吧,您没有将 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";
}

【讨论】:

    【解决方案2】:

    这是 SimpleXML 的一种特殊行为。

    如果您在 xml 中有一个孩子 - 您将在 json 中有一个对象,如果您有多个孩子 - 您将获得一组对象。所以,我建议你用简单的数组而不是 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]);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-05-05
      • 2013-08-28
      • 1970-01-01
      • 2017-07-01
      • 2012-08-07
      • 2018-05-19
      • 2023-04-02
      相关资源
      最近更新 更多