我有一个应用程序,需要存储多维数组到几个mysql表。当遍历数组时,我需要找到特定的键,将值插入数据库并将创建的DB ID传递给数组中的子元素。例如,如果有一个键"unit"找到它,获取标题,插入数据库,返回id,将id传递给下一次迭代。在下一次迭代中,我从单元获得id并搜索课程,保存具有单元id的课程。
数组的层次结构。
单位课
测试
——问题
——答案
下面是post表单输出的一个示例。有随机生成的id,因为表单是由用户动态创建的。我应该坚持使用for循环还是使用递归来解决我的问题?如果递归在这里是可能的,任何帮助是非常感激的。谢谢你。
Array
(
[unit] => Array
(
[fa53a225-e10c-408b-ad98-f3be26670587] => Array
(
[title] => Unit 1
[lesson] => Array
(
[ae89d2bd-bb06-42ed-be5d-76d450fa1d68] => Array
(
[title] => Lesson 1
)
[79245a3a-e3e8-4aa2-9b5b-35cef4740d93] => Array
(
[title] => Lesson 2
)
[34c30554-3b4c-4c5f-b398-4dbc7a2f2d00] => Array
(
[title] => Lesson 3
)
[28241d75-1733-47e1-aa34-133bc71ef382] => Array
(
[title] => Lesson 4
)
)
[quiz] => Array
(
[e93b5973-e13d-4a2d-a60a-4f86721b8f5a] => Array
(
[title] => Quiz 1
[question] => Array
(
[5e9d4f74-af08-430d-a405-e4d5464aff4a] => Array
(
[title] => Question 1
[type] => truefalse
[answer] => false
)
[b848cd75-bae4-44dd-99b0-ba041cd74b87] => Array
(
[title] => Question 2
[type] => truefalse
[answer] => true
)
[f5c72134-2de2-4fc4-8601-1776e43461e9] => Array
(
[title] => Question 3
[type] => multiple
[correct] => Array
(
[0] => 0
[1] => 1
)
[answer] => Array
(
[0] => answer 1
[1] => answer 2
[2] => answer 3
[3] =>
[4] =>
)
)
)
)
)
)
[a8a42316-f5fb-4b44-bd41-e19e8f3fb8e0] => Array
(
[title] => Unit 2
[lesson] => Array
(
[b438f957-7386-4202-8ff0-61fcdb020ba6] => Array
(
[title] => Lesson 1
)
[c6513c26-2d2f-4835-8fe7-9f4c82ea459d] => Array
(
[title] => Lesson 2
)
[d6853af6-e3a8-4e17-9df8-eeddb5859483] => Array
(
[title] => Lesson 3
)
)
[quiz] => Array
(
[96c1b4c2-1e00-4702-9064-25fcea6e10bb] => Array
(
[title] => Quiz 1
[question] => Array
(
[fc44b82e-089c-47b0-8404-9c12a9ecb2d6] => Array
(
[title] => question 1
[type] => truefalse
[answer] => true
)
)
)
)
)
)
)
我更喜欢递归,作为更灵活的方法
$structure = ["Unit"=>
["Lesson"=>[],
"Quiz"=>
["Question"=>
["Answers"=>[]]]]];
function insertItems($array, $parent_db_id, $structure) {
// at first step $object_name=Unit, at second Lesson, quiz
foreach ($structure as $object_name=>$next_level_structure) {
// loop through objects (at first step units, at second Lessons, quizes)
foreach ($array[$object_name] as $object_id=>$object) {
// ... insert in db $object_id, $object['title'], $parent_db_id etc
// retrieve $inserted_db_id ...
// next recursion level if next level not empty
if ($next_level_structure) {
insertItems($object, $inserted_db_id, $next_level_structure);
}
}
}
}
insertItem($data, null, $structure);