我有一个数据集,它是一个扁平的、分层的多维数组:
[
[
'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,它们包含其他子类别,而这些子类别又包含产品。
我试图遍历这个扁平数组,但出现了一些问题,因为'core i7'类别将不知道其父类别是'Skylake'。 当我将数据插入数据库时,其parent_id将为空。
/**
* 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为空值。
但我不知道原因所在。
createCatalog
是递归的。 - Don't Panic