更改JSON输出“格式” - PHP

时间:2017-10-21 20:03:18

标签: php arrays json

(我在PHP / JSON中有点新)我有一个PHP页面向我发送一个信息数组到Android应用程序,我需要更改Json“格式”,以便我可以在我的Android应用程序中管理它

我尝试将数组添加到PHP类中,但我只会收到错误。

由此(这只是一个例子):

 [
   {
      "updated_at":"2012-03-02 21:06:01",
      "fetched_at":"2012-03-02 21:28:37.728840",
      "description":null,
      "language":null,
      "title":"JOHN",
      "url":"http://rus.JOHN.JOHN/rss.php",
      "icon_url":null,
      "logo_url":null,
      "id":"4f4791da203d0c2d76000035",
      "modified":"2012-03-02 23:28:58.840076"
   },
   {
      "updated_at":"2012-03-02 14:07:44",
      "fetched_at":"2012-03-02 21:28:37.033108",
      "description":null,
      "language":null,
      "title":"PETER",
      "url":"http://PETER.PETER.lv/rss.php",
      "icon_url":null,
      "logo_url":null,
      "id":"4f476f61203d0c2d89000253",
      "modified":"2012-03-02 23:28:57.928001"
   }
]

对此(其他例子):

{"master":[
   {
      "updated_at":"2012-03-02 21:06:01",
      "fetched_at":"2012-03-02 21:28:37.728840",
      "description":null,
      "language":null,
      "title":"JOHN",
      "url":"http://rus.JOHN.JOHN/rss.php",
      "icon_url":null,
      "logo_url":null,
      "id":"4f4791da203d0c2d76000035",
      "modified":"2012-03-02 23:28:58.840076"
   },
   {
      "updated_at":"2012-03-02 14:07:44",
      "fetched_at":"2012-03-02 21:28:37.033108",
      "description":null,
      "language":null,
      "title":"PETER",
      "url":"http://PETER.PETER.lv/rss.php",
      "icon_url":null,
      "logo_url":null,
      "id":"4f476f61203d0c2d89000253",
      "modified":"2012-03-02 23:28:57.928001"
   }
]
}

我创建JSON数组的PHP页面:

<?php

    class card{

        public $id = 0;
        public $name = "";
        public $value = 0;
        public $imgpath = "";
        public $rarity = "";
        public $litness = 0;
        public $dankness = 0;
        public $expansion = "";


    }

    $b= array();

    $connessione = mysqli_connect("", "", "", "");

    $query = "insert_query_here";

    $risultato = mysqli_query($connessione, $query);
    while($row = mysqli_fetch_assoc($risultato)){

    $card = new card();
    $card->id = $row['id_card'];
    $card->name = $row['name'];
    $card->value = $row['value'];
    $card->imgpath = $row['imgpath'];
    $card->rarity = $row['name_rarity'];
    $card->litness = $row['litness'];
    $card->dankness = $row['dankness'];
    $card->expansion = $row['expansion_name'];

    $b[] = $card;

    }

    $out = array_values($b);
    print json_encode($out);

1 个答案:

答案 0 :(得分:2)

尝试以下方法:

$out = ['master' => array_values($b)];
print json_encode($out);

这将在主数组中添加键master,其余的将嵌套在其中。