如果您的问题是插入以下数据:
[{"id":1},{"id":2,"children":[{"id":3},{"id":4},{"id":5,"children":[{"id":6},{"id":7},{"id":8}]},{"id":9},{"id":10}]},{"id":11},{"id":12}]
进入所描述的数据库,然后我建议首先使用json_decode($given_data, true)
where 真实状态解析 JSON 以提供数组作为输出。然后递归遍历返回的树:
$given_data = '[{"id":1},{"id":2,"children":[{"id":3},{"id":4},{"id":5,"children":[{"id":6},{"id":7},{"id":8}]},{"id":9},{"id":10}]},{"id":11},{"id":12}]';
$given_arr = json_decode($given_data, true);
print_r($given_arr);
function create_categories(&$arr, $parent_id){
foreach($arr as $key => $item){
$id = $item["id"];
$sql = "INSERT INTO email_list (id, parent_id) values ('$id', '$parent_id');";
//mysql_query($sql) or exit(mysql_error());
echo $sql."\n";
if(isset($item['children'])){
create_categories($item['children'], $id);
}
}
}
create_categories($given_arr, 0);
输出以下内容:
Array
(
[0] => Array
(
[id] => 1
)
[1] => Array
(
[id] => 2
[children] => Array
(
[0] => Array
(
[id] => 3
)
[1] => Array
(
[id] => 4
)
[2] => Array
(
[id] => 5
[children] => Array
(
[0] => Array
(
[id] => 6
)
[1] => Array
(
[id] => 7
)
[2] => Array
(
[id] => 8
)
)
)
[3] => Array
(
[id] => 9
)
[4] => Array
(
[id] => 10
)
)
)
[2] => Array
(
[id] => 11
)
[3] => Array
(
[id] => 12
)
)
INSERT INTO email_list (id, parent_id) values ('1', '0');
INSERT INTO email_list (id, parent_id) values ('2', '0');
INSERT INTO email_list (id, parent_id) values ('3', '2');
INSERT INTO email_list (id, parent_id) values ('4', '2');
INSERT INTO email_list (id, parent_id) values ('5', '2');
INSERT INTO email_list (id, parent_id) values ('6', '5');
INSERT INTO email_list (id, parent_id) values ('7', '5');
INSERT INTO email_list (id, parent_id) values ('8', '5');
INSERT INTO email_list (id, parent_id) values ('9', '2');
INSERT INTO email_list (id, parent_id) values ('10', '2');
INSERT INTO email_list (id, parent_id) values ('11', '0');
INSERT INTO email_list (id, parent_id) values ('12', '0');