如何使用MySQL存储过程返回值数组?

时间:2016-11-22 06:39:41

标签: php mysql codeigniter stored-procedures

我没有存储过程(MySQL)的经验。我想按如下方式返回JSON数据,

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

这里我现在可以返回整个对象的数组。但我不知道如何在每个对象上返回子数组。

1 个答案:

答案 0 :(得分:0)

使用Codeigniter:

首先,在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 / welcome / 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"
     }
      ]
   }
]