[英]PHP how to iterate over hierarhical flat array?
我有這個數據集,這是一個平面的多維數組:
[
[
'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。
我認為問題是$ parentId將為Core i7歸零。
但我不明白為什么。
問題是您對當前類別的父級以及您在循環中創建的子$categoryId
的父級使用相同的變量$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;
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.