I am new to PHP
and JSON
. I want to convert my php array to json in the following format
my json file should look like following.
[
{
"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"
}
]
I have data in table, please tell me how can i form my php array so that it will get converted to above json file
Your array format should be in this format that i am showing as an example:
$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') )
Programmatic structure of the array example:
$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';
This was an example as per your question, you can dynamically assign the values in an loop using a counter.
Then json_encode
the array
$json = json_encode($arr);
You can forge your JSON with Simple JSON for PHP v3. It will also send the correct headers.
Here is a full example with a custom class
<?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();
?>
It results in :
[
{
"id": false,
"title": "All Day Event",
"start": "2015-02-01",
"end": false
},
{
"id": false,
"title": "All Day Event",
"start": "2015-02-07",
"end": "2015-02-10"
},
{
"id": 999,
"title": "Repeating Event",
"start": "2015-02-09T16:00:00-05:00",
"end": false
}
]