在PHP中生成所需的JSON格式

时间:2019-03-29 13:48:29

标签: php arrays json

我不熟悉php数组。因此,我无法解决该问题:

我的数据来自数据库。我没有发布数据库连接部件,它们工作正常。据我了解,我需要使用多维数组。我的Json格式应该是这样

{
   "monthly":[
      {
         "id":1,
         "name":"This is a JSON event",
         "startdate":"2016-9-15",
         "enddate":"2016-9-15",
         "starttime":"12:00",
         "endtime":"2:00",
         "color":"#FFB128",
         "url":""
      },
      {
         "id":2,
         "name":"This is a JSON event",
         "startdate":"2019-3-25",
         "enddate":"2019-3-25",
         "starttime":"12:00",
         "endtime":"23:00",
         "color":"#EF44EF",
         "url":""
      }
   ]
}

我的PHP脚本(相关部分):

try {
    $q = "SELECT * FROM eventcalendar";
    $res = $db->prepare($q);
    $res->execute();

    if ($res->rowCount() != 0) {
        $data = array('monthly' => array());
        $push_array = array();

        foreach ($res as $key) {
            $data['monthly']['id'] = $key['id'];
            $data['monthly']['name'] = $key['name'];
            $data['monthly']['startdate'] = $key['startdate'];
            $data['monthly']['enddate'] = $key['startdate'];
            $data['monthly']['color'] = $key['color'];
            $data['monthly']['starttime'] = 12;
            $data['monthly']['endtime'] = 12;
            $data['monthly']['url'] = "";

            array_push($push_array, $data);
        }

        file_put_contents('../js/events.json', json_encode($push_array));
        echo('<div class="alert alert-success resultsuccess" ><h4 class="alert-heading">Successful!</h4></div>');
    }
} catch (Exception $e) {
    echo('<div class="alert alert-danger resultsuccess" >'.'Error: '.$e->getMessage().'</div>');
}

我得到了JSON格式

[
   {
      "monthly":{
         "id":"1",
         "name":"test1",
         "startdate":"2019-03-29",
         "enddate":"2019-03-29",
         "color":"#ffb128",
         "starttime":12,
         "endtime":12,
         "url":""
      }
   },
   {
      "monthly":{
         "id":"2",
         "name":"test2",
         "startdate":"2019-03-29",
         "enddate":"2019-03-29",
         "color":"#4263e6",
         "starttime":12,
         "endtime":12,
         "url":""
      }
   }
]

感谢阅读...

1 个答案:

答案 0 :(得分:2)

您的问题是,每次循环创建的索引都是monthly,而不是将新数据推入现有的monthly数组中。尝试以下方法:

    if ($res->rowCount() != 0) {
        $push_array = array('monthly' => array());
        $data = array();
        foreach ($res as $key) {
            $data['id'] = $key['id'];
            $data['name'] = $key['name'];
            $data['startdate'] = $key['startdate'];
            $data['enddate'] = $key['startdate'];
            $data['color'] = $key['color'];
            $data['starttime'] = 12;
            $data['endtime'] = 12;
            $data['url'] = '';
            array_push($push_array['monthly'], $data);
        }