数组类别子类

时间:2018-02-26 16:17:37

标签: arrays perl

我有这个类别和子类别表。

NULL的值为parent_id的字段是一个类别,使用parent_id的字段是子类别。

我的树视图的子类别仅分配给类别,因此没有子类别的子类别。

+----+---------------------+-----------+
| id | name                | parent_id |
+----+---------------------+-----------+
|  1 | Laptop              |      NULL |
|  2 | TV                  |      NULL |
|  3 | Tablet & Mobile     |      NULL |
|  4 | PC                  |      NULL |
|  5 | Laptops             |         1 |
|  6 | Laptop accessories  |         1 |
|  7 | TV accessories      |         2 |

如果我执行SELECT *并使用while加注它,我会得到以下数组。

'category' => [
              {
                'name' => 'Laptop',
                'id' => '1',
                'parent_id' => undef
              },
              {
                'name' => 'TV',
                'id' => '2',
                'parent_id' => undef
              },
              {
                'name' => 'Table & mobile',
                'id' => '3',
                'parent_id' => undef
              },
              {
                'name' => 'PC',
                'id' => '4',
                'parent_id' => undef
              },
              {
                'name' => 'Laptops',
                'id' => '5',
                'parent_id' => '1'
              },
              {
                'name' => 'Laptop accessories ',
                'id' => '6',
                'parent_id' => '1'
              },
              {
                'name' => 'TV accessories',
                'id' => '7',
                'parent_id' => '2'
              }

我正在寻找的结构应该是这样的。

category 1
-- subcategory 1.1
-- subcategory 1.2
category 2
-- subcategory 2.1

我现在得到的是

category 1
subcategory 1.1
category 2
subcategory 1.2
subcategory 2.1

1 个答案:

答案 0 :(得分:-1)

#!/usr/bin/perl
use strict;
use warnings;
my %struct = (category => [
    {
        'name' => 'Laptop',
        'id' => '1',
        'parent_id' => undef
    },
    {
        'name' => 'TV',
        'id' => '2',
        'parent_id' => undef
    },
    {
        'name' => 'Table & mobile',
        'id' => '3',
        'parent_id' => undef
    },
    {
        'name' => 'PC',
        'id' => '4',
        'parent_id' => undef
    },
    {
        'name' => 'Laptops',
        'id' => '5',
        'parent_id' => '1'
    },
    {
        'name' => 'Laptop accessories ',
        'id' => '6',
        'parent_id' => '1'
    },
    {
        'name' => 'TV accessories',
        'id' => '7',
        'parent_id' => '2'
    }
]);


my %tree;
for my $cat (grep ! defined $_->{parent_id}, @{ $struct{category} }) {
    $tree{ $cat->{id} } = $cat;
}

for my $cat (grep defined $_->{parent_id}, @{ $struct{category} }) {
    $tree{ $cat->{parent_id} }{subcat}{ $cat->{id} } = $cat;
}

use Data::Dumper; print Dumper \%tree;