要了解我想做什么,这里有一个简单的解释:我想创建模板。
一个"template"有一个“面板” 这个“面板”有一些“项目”和另一个“面板” 我们必须一步一步地做,直到最后一个“Item”
我想要这样的东西:
- Template
- Panel "Section"
- Panel "Slider"
- Panel "Slide 1"
- Item "Text 1"
- Item "Text 2"
- Item "Button"
- Panel "Slide 2"
- Panel "Buttons"
- Item "Button 1"
- Item "Button 2"
- Item "Text"
通过 Laravel 的多态关系,我有 3 个模型,分别是“Panel”、“Item”和“PanelContent”(这个模型有一些属性“parent_id”、“contentable_id 和”contentable_type”有助于知道哪个 Panel 是parent,以及哪个 Item 或 Panel 将是内容。
显然,我的模型包含一些对获取内容和父级有用的函数。
我做了什么
目前,我使用递归函数让 Panel 的子级逐步构建具有我在开始时显示的结构的数组。
private function getChildren(PanelContent $panelContent, string $parentName, string $key): void
{
$this->result['template']['global_panel'][$parentName][$key] = $panelContent->contentable->toArray();
if ($panelContent->contentable_type === 'panel') {
foreach($panelContent->contentable->contents as $key => $container) {
$this->getChildren($container, $container->contentable->name, $key);
}
}
}
我想要什么
我想要这样的东西,比如树状结构。
$this->result = [
'template' => [
'id' => 1,
'name' => 'MySlider'
'contents' => [
'id' => 745,
'name' => 'slider',
'type' => 'panel',
'slides' => [
0 => [
'id' => 500,
'name' => 'slide',
'type' => 'panel'
'buttons' => [
0 => [
'id' => 877,
'name' => 'button',
'type' => 'item'
]
]
],
1 => [
'id' => 500,
'name' => 'slide',
'type' => 'panel'
'buttons' => [
0 => [
'id' => 877,
'name' => 'button',
'type' => 'item'
]
]
]
]
]
]
];
我现在有什么
目前,我有这样的东西:
$this->result = [
'template' => [
'id' => 1,
'name' => 'MySlider'
'contents' => [
'id' => 745,
'name' => 'slider',
'type' => 'panel'
],
'slides' => [
0 => [
'id' => 500,
'name' => 'slide',
'type' => 'panel'
],
1 => [
'id' => 500,
'name' => 'slide',
'type' => 'panel'
]
],
'buttons' => [
0 => [
'id' => 877,
'name' => 'button',
'type' => 'item'
],
1 => [
'id' => 877,
'name' => 'button',
'type' => 'item'
]
]
]
];
使用这段代码,结果是“正常”的,因为这一行的键是错误的:
$this->result['template']['global_panel'][$parentName][$key] = $panelContent->contentable->toArray();
但我真的不知道如何用我的数据做我想做的事。 我希望我的解释没问题。你有什么想法吗?如何正确构建我的数组(当然是 json)?
谢谢你,祝你有愉快的一天!
最佳答案
我找到了解决方案。 Laravel 有很多助手,其中有一个用于数组。
private function formatTemplateData(PanelContent $panelContent, string $path): void
{
Arr::set(
$this->result,
'template.data.' . $path,
"Je suis une data"
);
if ($panelContent->contentable_type === 'panel') {
foreach($panelContent->contentable->contents as $container) {
$newPath = $path . '.' . $container->contentable->name . $container->contentable->order;
$this->formatTemplateData($container, $newPath);
}
}
}
通过“set”函数,我可以使用字符串为我的数组创建动态路径。 例如:
"template.data.slider.slide.0.test"
将是:
$array['template']['data']['slider']['slide'][0]['test']
感谢您的帮助。
关于php - 具有多态关系的多维数组(树结构),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58873776/