2016-11-22 90 views
0

我沒有關於存儲過程(MySQL)的經驗。我想如下返回JSON數據,如何使用MySQL存儲過程返回值數組?

[ 
    { 
    'id': 1, 
    'name': 'ABC', 
    'children': [ 
     { 
     'id': 1, 
     'name': 'Ana', 
     'sex': 1 
     }, 
     { 
     'id': 2, 
     'name': 'John', 
     'sex': 0 
     }, 
     { 
     'id': 3, 
     'name': 'Max', 
     'sex': 0 
     } 
    ] 
    }, 
    { 
    'id': 2, 
    'name': 'XYZ', 
    'children': [ 
     { 
     'id': 1, 
     'name': 'Bob', 
     'sex': 1 
     }, 
     { 
     'id': 2, 
     'name': 'Mike', 
     'sex': 0 
     }, 
     { 
     'id': 3, 
     'name': 'Sara', 
     'sex': 1 
     } 
    ] 
    } 
] 

我的表

父表

id int 10, 
name varchar 30 

子表

id int 10, 
name varchar 30, 
sex tinyint 1, 
parent_id int 10 

在這裏,我可以返回的整個陣列現在的對象。但我不知道如何返回每個對象內的子數組。

請幫我實現這個

+0

什麼語言是您使用? (php,java ...),因爲MySQL沒有JSON函數 –

+0

帶CodeIgnitor的PHP – Prince

回答

0

使用笨:

首先,兩個查詢的parentchild表型號:

class Json_model extends CI_Model { 

    public function get_hierarchy_json(){ 

     //get all records from `parent` 
     $sql = "select * from parent order by id"; 
     $parent = $this->db->query($sql)->result(); 

     //get all records from `child` 
     $sql = "select * from child order by parent_id"; 
     $childs = $this->db->query($sql)->result(); 

     //build the hierarchy tree comparing parent.id and child.parent_id 
     $current_parent = 0; 

     foreach ($childs as $index => $child) { 
      if ($parent[$current_parent]->id == $child->parent_id) { 
       $parent[$current_parent]->childs[] = $child; 
      }else{ 
       while (isset($parent[$current_parent]) && 
         $parent[$current_parent]->id != $child->parent_id) { 

        $current_parent++; 
       } 
       $parent[$current_parent]->childs[] = $child; 
      } 
     } 
     return $parent; 
    } 
} 

其次,打印模型結果控制器作爲json格式的文本:

class Welcome extends AppController { 

    public function __construct(){ 
     $this->load->model('json_model'); 
    } 

    public function json_test(){ 

     echo json_encode($this->json_model->get_hierarchy_json()); 
    } 
} 

三,打開URL /首頁/ json_test瞧:

[ 
    { 
     "id":"1", 
     "name":"ABC", 
     "childs":[ 
    { 
     "id":"1", 
     "name":"Ana", 
     "sex":"1", 
     "parent_id":"1" 
    }, 
    { 
     "id":"2", 
     "name":"Jhon", 
     "sex":"0", 
     "parent_id":"1" 
    }, 
    { 
     "id":"3", 
     "name":"Max", 
     "sex":"0", 
     "parent_id":"1" 
    } 
     ] 
    }, 
    { 
     "id":"2", 
     "name":"XYZ", 
     "childs":[ 
    { 
     "id":"4", 
     "name":"Bob", 
     "sex":"1", 
     "parent_id":"2" 
    }, 
    { 
     "id":"5", 
     "name":"Mike", 
     "sex":"0", 
     "parent_id":"2" 
    }, 
    { 
     "id":"6", 
     "name":"Sara", 
     "sex":"1", 
     "parent_id":"2" 
    } 
     ] 
    } 
]