以特定格式将PHP传递给JSON

时间:2013-12-03 07:54:58

标签: php json

我目前正在将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"
            }
        ]
    }

我现在已经尝试了将近一天,感到非常愚蠢,我只是缺少[]

任何帮助都非常赞赏。

2 个答案:

答案 0 :(得分:1)

构造如下:

    $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);

答案 1 :(得分:0)

在这里: -

将结果数组放在数组中。

$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);