2016-11-22 7 views
0

私はストアドプロシージャ(MySQL)の経験がありません。私はMySQLストアドプロシージャを使用して値の配列を返すにはどうすればよいですか?

親テーブルが

id int 10, 
name varchar 30 
私のテーブル

[ 
    { 
    '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データを返すようにしたい子テーブルここ

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

私は、全体の配列を返すことができますオブジェクトは今です。しかし、私は各オブジェクトの内側に子配列を返す方法を知らない。

CodeIgniterのを使用して、この

+0

どのような言語を使用していますか? (PHP、java ...)MySQLにはJSON関数がないので、 –

+0

PHP with CodeIgnitor – Prince

答えて

0

を達成するために私を助けてください:

まず、parentchildテーブル上の2つのクエリとモデル:

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

第3に、オープン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" 
    } 
     ] 
    } 
] 
関連する問題