【发布时间】:2019-09-25 18:07:38
【问题描述】:
我正在构建一个通用数据库播种器,其中根据给定的输入(数组)播种一些表。目前我有一个嵌套 1 级深的数组:
$topics = [
'Array value 1',
'Array value 2',
'Array key value 1' => [
'Nested array value 1',
'Nested array value 2',
],
'Array key value 2' => [
'Nested array value 3',
],
];
在我的播种机中,我循环浏览这个主题数组。如果主题是键,则它是父级,我需要保存其 ID 以将其分配给子级。例如:'Array key value 1'的ID需要传递给'Nested array value 1',因为它们是相连的。我现在这样做的方式是这样的:
// Define seeders.
$topicSeeder = new TopicTableSeeder;
$agendaPointSeeder = new AgendaPointTableSeeder;
// Get all the Topics and create Agenda Points.
foreach ($topics as $key => $topic) {
// Check if Topic is an array.
if (is_array($topic)) {
// If Topic is a key, it is a Parent.
if ($key) {
// Topic is Parent so set parentId to NULL and save own ID.
$parentAgendaPointId = NULL;
// Execute Topic and Agenda Point seeders.
$topicId = $topicSeeder->run($organizationId, $key);
$parentAgendaPointId = $agendaPointSeeder->run($parentAgendaPointId);
}
// If Topic is an array but not a key, it is a Child and gets the parentId.
for ($i = 0; $i < count($topic); $i++) {
$topicId = $topicSeeder->run($organizationId, $topic[$i]);
$agendaPointSeeder->run($parentAgendaPointId);
}
} else {
// Topic isn't an array so it should have no Parent.
$parentAgendaPointId = NULL;
$topicId = $topicSeeder->run($topic);
$agendaPointSeeder->run($parentAgendaPointId);
}
}
问题是,当数组嵌套的层次越深时,上面代码中的 foreach 就不再起作用了。例如这个数组:
$topics = [
'Unnested topic',
'Unnested topic 2',
'Key topic' => [
'Nested topic',
'Nested topic 2',
],
'Key topic 2' => [
'Nested key topic' => [
'Nested topic 3',
],
],
];
我怎样才能使这个递归,但当它是一个子值时仍然有能力做某事?欢迎任何想法或建议,因为我现在有点卡住了。
【问题讨论】:
-
确切的问题是什么?您的代码似乎缺少递归调用(或者显示的代码可能不完整)。你说
but remain the ability to do something when it's a child value,所以你正确地检查了is_array(),并检测到当前主题是父主题。