2016-11-22 1 views
0

저장 프로 시저 (MySQL)에 대한 경험이 없습니다. 나는MySQL 저장 프로 시저를 사용하여 값 배열을 반환하려면 어떻게해야합니까?

부모 테이블

id int 10, 
name varchar 30 

자식 테이블이 여기에

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

내가 전체의 배열을 반환 할 수 있습니다

[ 
    { 
    '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 
     } 
    ] 
    } 
] 

내 테이블, 다음과 같이 JSON 데이터를 반환 할 지금 객체. 하지만 각 객체에 자식 배열을 반환하는 방법을 모르겠습니다.

달성하기 위해 제발 도와주세요이 CodeIgniter를 사용

+0

어떤 언어를 사용하고 있습니까? (PHP, java ...) MySQL에는 JSON 함수가 없으므로 –

+0

PHP with CodeIgnitor – Prince

답변

0

:

첫째, parent에 두 개의 질의와 child 테이블 모델 :

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" 
    } 
     ] 
    } 
] 
관련 문제