2
我想從dbix :: class結果集中構建一個樹狀的嵌套數據結構。問題是,當涉及到超過1個更深一層的元素,我得到異常:子程序返回空字符串而不是哈希引用
不能使用字符串(「」)作爲HASH裁判而「嚴格裁判」在使用中 /家/ ROMEL /應用/ MyApp的/腳本/../ LIB/MyApp的/ Products.pm線38
的代碼包含兩個子程序:使用Data ::打印機
sub _findparent {
my ($tree, $pid) = @_;
if (my ($parent) = grep { $_->{'id'} == $pid } @$tree) {
say "found parent $parent->{'id'} = $pid ($parent->{'name'})";
$parent->{'children'} = [] if (ref $parent->{'children'} ne 'ARRAY');
return $parent;
} else {
for my $i (@$tree) {
say "traversing $i->{'name'} $i->{'id'}";
_findparent($i->{'children'}, $pid) if (ref $i->{'children'} eq 'ARRAY');|
}
}
}
sub index {
my $self = shift;
my @data = $self->db->resultset('Category')->search();
my @tree;
for my $i (@data) {
my $i = $i->get_column_data;
if (my $parent_id = $i->{'parent_id'}) {
say "--- $i->{'name'} has parent (id $parent_id), searching";
#if (my $parent = _findparent(\@tree, $parent_id)) {
# push ($parent->{'children'}, $i);
#}
push (_findparent(\@tree, $parent_id)->{'children'}, $i);
} else {
$i->{'children'} = [];
push (@tree, $i);
say "adding \"$i->{name}\" to tree as root";
}
}
$self->render(menudata => [@tree]);
}
的@tree傾倒:
[
[0] {
children [
[0] {
children [],
created_on undef,
id 2,
modified_on undef,
name "children 1 level",
parent_id 1,
position undef,
user_id undef
}
],
created_on undef,
id 1,
modified_on undef,
name "parent category one",
parent_id undef,
position undef,
user_id undef
},
[1] {
children [
[0] {
children [],
created_on undef,
id 4,
modified_on undef,
name "children 1 level 2",
parent_id 3,
position undef,
user_id undef
},
[1] {
children [],
created_on undef,
id 5,
modified_on undef,
name "children 1 level 3",
parent_id 3,
position undef,
user_id undef
},
[2] {
created_on undef,
id 12,
modified_on undef,
name "children 1 level 4",
parent_id 3,
position undef,
user_id undef
}
],
created_on undef,
id 3,
modified_on undef,
name "parent category two",
parent_id undef,
position undef,
user_id undef
}
]
最後的表結構:38
+-------------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------------+-------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| name | varchar(45) | YES | | NULL | |
| user_id | int(11) | YES | MUL | NULL | |
| created_on | datetime | YES | | NULL | |
| modified_on | datetime | YES | | NULL | |
| position | varchar(45) | YES | | NULL | |
| parent_id | varchar(45) | YES | | NULL | |
+-------------+-------------+------+-----+---------+----------------+
線是嵌套的元素不止一層深的一個
push (_findparent(\@tree, $parent_id)->{'children'}, $i);
所以_findparent
不返回任何東西。
您在'_findparent'的'else'分支中沒有顯式返回。在這種情況下找出你真正想要返回的東西,並將其明確。 – amon
謝謝。但是如果我不想在那裏返回任何東西,只需使用grep更深一層執行另一個搜索? – romel
當然可以:您想要返回適當的父節點。您也不處理樹中任何位置不存在該ID的情況。你有使用樹數據結構和遞歸函數的經驗嗎? – amon