[
[
'title' => 'Skylake',
'type' => 'category',
'items' =>
[
[
'title' => 'Core i3',
'type' => 'category',
'items' =>
[
[
'title' => '6100',
'type' => 'product',
'price' => 100.0,
],
[
'title' => '6300',
'type' => 'product',
'price' => 110.0,
],
],
],
[
'title' => 'Core i7',
'type' => 'category',
'items' => [
[
'title' => '7700',
'type' => 'product',
'price' => 330.0,
],
[
'title' => '7700K',
'type' => 'product',
'price' => 370.0,
],
],
],
],
],
[
'title' => 'KabyLake',
'type' => 'category',
]
];
如您所见,有两个主要类别:Skylake和Kabylake,它们包含其他子类别,而子类别包含产品.
我尝试遍历此平面数组,但是出了点问题,因为“核心i7”类别将不知道其父级是“ Skylake”.
当我将数据插入数据库时,其parent_id将为null.
/**
* Creates catalog.
* @param mixin $sampleItems sample items
* @param interger $categoryId id of category (parent id)
*/
private function createCatalog(&$sampleItems, $categoryId = null)
{
foreach ($sampleItems as $sampleItem) {
if ($sampleItem['type'] == 'category') {
$categoryId = $this->createCategory($sampleItem, $categoryId);
} else {
$this->createProduct($sampleItem, $categoryId);
}
$hasItems = isset($sampleItem['items']) && is_array($sampleItem['items']);
if ($hasItems) {
$this->createCatalog($sampleItem['items'], $categoryId);
$categoryId = null;
}
}
}
/**
* Create category.
* @param mixin $sampleData
* @param integer $parentId ID of parent category
* @return integer ID of created category
*/
private function createCategory($sampleData, $parentId)
{
$category = new Category();
if ($parentId !== null) {
$category->parent_id = $parentId;
}
$category->title = $sampleData['title'];
$category->status = 1;
$category->save();
return $category->id;
}
/**
* Create Product.
* @param mixin $sampleData
* @param integer $categoryId
*/
private function createProduct($sampleData, $categoryId)
{
$product = new Product();
if ($categoryId !== null) {
$product->category_id = $categoryId;
}
$product->title = $sampleData['title'];
$product->price = $sampleData['price'];
$product->description = $sampleData['description'];
$product->status = 1;
$product->save();
}
不幸的是,这是数据库中的当前层次结构:
Skylake
Core i3
Core i7
KabyLake
Core i7应该在Skylake下.
我认为问题在于Core i7的$parentId将为null.
但是我不明白为什么.
解决方法:
问题在于,您为当前类别的父级和循环中创建的子类别的父级使用了相同的变量$categoryId.当您执行$categoryId = null;创建嵌套目录后,将影响对createCategory()的下一次调用.
使用其他变量,我在下面使用$subcat.
private function createCatalog(&$sampleItems, $categoryId = null)
{
$subcat = null;
foreach ($sampleItems as $sampleItem) {
if ($sampleItem['type'] == 'category') {
$subcat = $this->createCategory($sampleItem, $categoryId);
} else {
$this->createProduct($sampleItem, $categoryId);
}
$hasItems = isset($sampleItem['items']) && is_array($sampleItem['items']);
if ($hasItems) {
$this->createCatalog($sampleItem['items'], $subcat);
$subcat = null;
}
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。