2016-11-16 47 views
1

我想從我的查詢中創建json數據。但我無法得到我的JSON數據,因爲我預計。請幫忙。這是我試過的代碼。 (它看起來像你的職位主要是代碼,請添加更多的細節是否足夠?)從活動記錄中獲取json數據

<?php 
     $this->db->select('campus.*, class.*'); 
     $this->db->from('campus'); 
     $this->db->join('class', 'campus.id = class.campus_id'); 
     $campus_info = $this->db->get()->result_array(); 
     foreach ($campus_info as $row) { 
      $var[]['id'] = $row['id']; 
      $var[]['campus_name'] = $row['campus_name']; 
      $var[]['class_id'] = $row['class_id'];   
      $var[]['class_name'] = $row['name']; 
     } 
     $json_data = json_encode($var, JSON_PRETTY_PRINT); 
     echo '<pre>'; 
     echo $json_data; 
     echo '</pre>'; 
     exit(); 

我的查詢結果是

Array 
(
    [0] => Array 
     (
      [id] => 4 
      [campus_name] => Test Campus Name 
      [institute_name] => Test Institute Name 1 
      [class_id] => 11 
      [name] => STD - VIII 
      [campus_id] => 4 
      [name_numeric] => 8 
      [teacher_id] => 6 
     ) 

    [1] => Array 
     (
      [id] => 4 
      [campus_name] => Test Campus Name 
      [institute_name] => Test Institute Name 1 
      [class_id] => 15 
      [name] => A' Level 
      [campus_id] => 4 
      [name_numeric] => 12 
      [teacher_id] => 6 
     ) 

想讓它JSON像

[{ 
    "id": "7", 
    "campus_name": "Azimpur", 
    "class_id": "9", 
    "class_name": "STD - VI" 
} 
{ 
    "id": "8", 
    "campus_name": "Azimpur", 
    "class_id": "10", 
    "class_name": "STD - VII" 
}] 

但是獲得

[ 
    { 
     "id": "4" 
    }, 
    { 
     "campus_name": "Test Campus Name" 
    }, 
    { 
     "class_id": "11" 
    }, 
    { 
     "class_name": "STD - VIII" 
    }, 
    { 
     "id": "4" 
    }, 
    { 
     "campus_name": "Test Campus Name" 
    }, 

回答

2

這是你的問題:

foreach ($campus_info as $row) { 
    $var[]['id'] = $row['id']; 
    $var[]['campus_name'] = $row['campus_name']; 
    $var[]['class_id'] = $row['class_id'];   
    $var[]['class_name'] = $row['name']; 
} 

在這裏,您將4個元素添加到您的$var變量的最高級別。

只應添加一個元素:

foreach ($campus_info as $row) { 
    $var[] = [ 
    'id' => $row['id'], 
    'campus_name' => $row['campus_name'], 
    'class_id' => $row['class_id'],  
    'class_name' => $row['name'] 
    ]; 
} 

如果你只選擇你需要的列,您可以將此減少到:

foreach ($campus_info as $row) { 
    $var[] = $row; 
} 

,甚至進一步,如果你的數據庫API有fetchAll方法。

+1

非常感謝,它的工作原理。 –