将PHP转换为特定格式的JSON


Pasing PHP to JSON in a specific Format

我目前正在将PHP解析为JSON,如下所示:

public function display($tpl = null){
        $this->items = $this->get('Events');
        $response = array();
        foreach ($this->items as $row) {
            $response[] = array(
                    'success'=>1,
                    'result'=> array(
                        'id' => $row->id,
                        'title' => $row->title,
                        'url' => 'http://www.example.co.za',
                        'class'=> "event-warning",
                        'start' => strtotime($row->date_start),
                        'end' => strtotime($row->date_end)
                    )
            );
        }
        echo json_encode($response);
    }

结果是:

[
   {
      "success":1,
      "result":{
         "id":"1",
         "title":"Event 3",
         "url":"http://www.example.com/",
         "class":"event-warning",
         "start":1386021600,
         "end":1388497860
      }
   }
]

但我需要格式化的方式是:

 {
        "success": 1,
        "result": [
            {
                "id": "295",
                "title": "Event 3",
                "url": "http://www.example.com/",
                "class": "event-important",
                "start": "1364320800000",
                "end":   "1364407286400"
            }
        ]
    }

我已经试了快一天了,我觉得很愚蠢,我只是错过了[]

非常感谢任何帮助。

构造如下:

    $response = array('success'=>1, 'result' => array());
    foreach ($this->items as $row) {
        $response['result'][] = array(
                    'id' => $row->id,
                    'title' => $row->title,
                    'url' => 'http://www.example.co.za',
                    'class'=> "event-warning",
                    'start' => strtotime($row->date_start),
                    'end' => strtotime($row->date_end)
        );
    }
    echo json_encode($response);

如下:--

只需将结果数组放入数组中即可。

$response[] = array(
                    'success'=>1,
                    'result'=> array(array(
                        'id' => '',
                        'title' => 'gbdf',
                        'url' => 'http://www.example.co.za',
                        'class'=> "event-warning",
                        'start' => 'dfbxd',
                        'end' => 'gbfbxf'
                    ))
            );
echo json_encode($response);