dtkjthe4025 2017-02-10 22:02 采纳率: 0%
浏览 22
已采纳

PHP如何迭代分层平面数组?

I have this data set, which is a flat hierarhical multi-dimensional 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',
    ]
];

As you can see there are two main category: Skylake and Kabylake, and these contains other subcategories and subcategories contain products.

I have tried to iterate over this flat array, but something went wrong, because the 'core i7' category will not know that its parent is 'Skylake'. When I insert the data into the database its parent_id will be 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();
    }

Unfortunately this is the current hierarchy in the database:

Skylake
  Core i3
Core i7
KabyLake

The Core i7 should be under the Skylake.

I think the problem is that $parentId will null for Core i7.

But I do not see why.

  • 写回答

1条回答 默认 最新

  • dplm47571 2017-02-10 22:25
    关注

    The problem is that you're using the same variable $categoryId for the parent of the current category and for the parents of the sub-categories that you're creating in the loop. When you do $categoryId = null; after creating a nested catalog, that affects the next call to createCategory().

    Use a different variable, I use $subcat below.

    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;
            }
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题