以下列格式将php转换为json

时间:2015-05-16 07:38:53

标签: php json

我是 PHP JSON 的新手。 我想以下列格式将我的php数组转换为json

我的json文件应如下所示。

[
  {
    "title": "All Day Event",
    "start": "2015-02-01"
  },
  {
    "title": "Long Event",
    "start": "2015-02-07",
    "end": "2015-02-10"
  },
  {
    "id": "999",
    "title": "Repeating Event",
    "start": "2015-02-09T16:00:00-05:00"
  },
  {
    "id": "999",
    "title": "Repeating Event",
    "start": "2015-02-16T16:00:00-05:00"
  },
  {
    "title": "Conference",
    "start": "2015-02-11",
    "end": "2015-02-13"
  },
  {
    "title": "Meeting",
    "start": "2015-02-12",
    "end": "2015-02-12"
  },
  {
    "title": "Lunch",
    "start": "2015-02-12T12:00:00-05:00"
  },
  {
    "title": "Meeting",
    "start": "2015-02-12"
  },
  {
    "title": "Happy Hour",
    "start": "2015-02-12T17:30:00-05:00"
  },
  {
    "title": "Dinner",
    "start": "2015-02-12T20:00:00"
  },
  {
    "title": "Birthday Party",
    "start": "2015-02-13T07:00:00-05:00"
  },
  {
    "title": "Click for Google",
    "url": "http://google.com/",
    "start": "2015-02-28"
  }
]

我有表中的数据,请告诉我如何形成我的php数组,以便它将转换为上面的json文件

2 个答案:

答案 0 :(得分:0)

您的数组格式应采用我作为示例显示的格式:

$arr = array( 0=>array('title'=>All Day Event,'start'=>'2015-02-07','end'=>'2015-02-10'),1=>array('title'=>All Day Event,'start'=>'2015-02-07','end'=>'2015-02-10') )

数组示例的编程结构:

$arr[0]['title']='All Day Event';
$arr[0]['start']='2015-02-07';
$arr[0]['end']='2015-02-10';
$arr[1]['title']='All Day Event';
$arr[1]['start']='2015-02-07';
$arr[1]['end']='2015-02-10';

根据您的问题,这是一个示例,您可以使用计数器在循环中动态分配值。

然后json_encode数组

$json = json_encode($arr);

答案 1 :(得分:0)

您可以使用Simple JSON for PHP v3伪造JSON。它还会发送正确的标题。

以下是自定义类

的完整示例
16

结果是:

<?php
  // The only include you need
  include('../includes/json.php');

  class dataConstructor extends content {
    public function __construct($title, $start = false, $end = false, $id = false){
      $json = new json();
      $json->add('id', $id);
      $json->add('title', $title);
      $json->add('start', $start);
      $json->add('end', $end);
      $this->json = $json->make();
    }
    public function get(){
      return $this->json;
    }
  }

  $json = new json();

  //for ($results ...) // Grab data from bdd
  //...
  $data = new dataConstructor('All Day Event','2015-02-01');
  $json->add('data', $data->get(), false);
  //...
  $data = new dataConstructor('All Day Event', '2015-02-07', '2015-02-10');
  $json->add('data', $data->get(), false);
  //... 
  $data = new dataConstructor('Repeating Event', '2015-02-09T16:00:00-05:00', false, 999);
  $json->add('data', $data->get(), false);
  //}

  $json->send_array();
?>
相关问题