2016-09-26 58 views
-1

我有以下功能,對我產生數據:清理的Json URL數據

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

JSON的輸出如下的格式如下:

[{"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)\/"}]}] 

我想清理數據所以我得到這樣的事情:

[{"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)/"}]}] 

請告訴我如何清潔JSON數據?

+5

http://stackoverflow.com/questions/10210338/json-encode-escaping-forward-slashes –

+2

你做錯了。你正在做'echo json_encode(..)'在你的循環中,所以你正在生成多個獨立的json字符串。你需要在循環內建立一個數組/對象。在建築完成時,您只能在流程結束時進行編碼。 –

回答

0

大部分代碼是冗餘/無用的。你可以平凡保存自己的行很多 像這樣的東西:

$sql = "SELECT project_name AS name, ... UNIX_TIMESTAMP(end_date) AS end_date etc..."; 

while($row = fetch()) { 
    $array[] = $row; 
} 

echo json_encode($array); 

構建一個對象,只是讓你可以將它強制轉換爲一個數組,是完全浪費和混亂。如果你想要一個數組,然後構建一個數組。完成「給我一個額外的生菜bigmac」,然後將其轉換爲魚片之後。