我有这个数组 我如何将这些数据插入数据库? 以及我如何检查数组中的任何项是否有[children]
我想使用
将数据插入数据库id,parent_id,level,order
注意:有些项目有子项目,有些项目没有,有些子项目有子项目 我的数组中有7个级别
Array
(
[0] => Array
(
[id] => 5
[children] => Array
(
[0] => Array
(
[id] => 4
[children] => Array
(
[0] => Array
(
[id] => 11
)
)
)
)
)
[1] => Array
(
[id] => 7
[children] => Array
(
[0] => Array
(
[id] => 9
)
)
)
[2] => Array
(
[id] => 6
)
[3] => Array
(
[id] => 8
)
[4] => Array
(
[id] => 10
)
)
答案 0 :(得分:0)
使用如下的递归(我不知道order
应该是什么意思,所以它被遗漏了。)
function insert_array( $children, $parent_id, $level ){
foreach( $children as $child ){
insert_array_item(
$child,
$parent_id,
$level
);
}
}
function insert_array_item( $item, $parent_id, $level ){
//you need to get the $db here first
$statement = $db->prepare(
"INSERT INTO `table`
VALUES (:id, :parent_id, :level )
"
);
$statement->bindParam( ':id', $item['id'] );
$statement->bindParam( ':parent_id', $parent_id );
$statement->bindParam( ':level', $level );
$statement->execute();
if( isset( $item['children'] ) ){
insert_array(
$item['children'],
$parent_id = $item['id'],
$level + 1
);
}
}
insert_array( $array, 0, 0 );