-1

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 ?

2
  • 5
    stackoverflow.com/questions/10210338/… Commented Sep 26, 2016 at 19:59
  • 2
    You're doing it wrong. You're doing echo json_encode(..) INSIDE your loop, so you're producing multiple independent json strings. You need to build an array/object inside the loop. You only encode at the END of the process, when the building is done. Commented Sep 26, 2016 at 20:02

1 Answer 1

0

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.