This question already has an answer here:
I have the following function that generates data for me :
function get_project_time() {
$name;
$desc;
$values;
$to;
$from;
$sql = $this->db->query("Select * from tbl_project")->result();
foreach ($sql as $value) {
$name = $value->project_name;
$desc = $value->project_status;
$start_date = $value->start_date;
$end_date = $value->end_date;
$unix_start_date = strtotime($start_date);
$unix_end_date = strtotime($end_date);
$to = "Date($unix_start_date)/";
$from = "Date($unix_end_date)/";
$e = new stdClass();
$f = new stdClass();
$e->name = $name;
$e->desc = $desc;
$f->to = $to;
$f->from = $from;
$e->values = array($f);
echo json_encode(array($e));
}
}
The json output looks in the following format :
[{"name":"e-Campus and eLearning Project","desc":"in_progress","values":[{"to":"\/Date(1473627600)\/","from":"\/Date(1480626000)\/"}]}][{"name":"BloodLink Training Project","desc":"in_progress","values":[{"to":"\/Date(1474405200)\/","from":"\/Date(1475010000)\/"}]}][{"name":"Test Project","desc":"","values":[{"to":"\/Date(1474405200)\/","from":"\/Date(1475182800)\/"}]}]
I would like to clean up the data so that I get something like this :
[{"name":"e-Campus and eLearning Project","desc":"in_progress","values":[{"to":"/Date(1473627600)/","from":"/Date(1480626000)/"}]}][{"name":"BloodLink Training Project","desc":"in_progress","values":[{"to":"/Date(1474405200)/","from":"/Date(1475010000)/"}]}][{"name":"Test Project","desc":"","values":[{"to":"/Date(1474405200)/","from":"/Date(1475182800)/"}]}]
Please advise on how I can clean the json Data ?
</div>
Most of that code is redundant/useless. You could trivially save yourself a lot of lines with something like this:
$sql = "SELECT project_name AS name, ... UNIX_TIMESTAMP(end_date) AS end_date etc...";
while($row = fetch()) {
$array[] = $row;
}
echo json_encode($array);
Building an object, just so you can typecast it to an array, is utterly wasteful and confusing. If you want an array, then build an array. Done do "Give me a bigmac with extra lettuce" and then convert it to a filet 'o fish afterwards.