【发布时间】:2013-09-24 04:27:24
【问题描述】:
我希望每个键的所有节点都按哈希引用或数组或类似的键排序,以便我可以根据需要对其进行迭代,因为我必须显示每个键及其所有子项。 以下是我的数据结构:
$hash1 = {
'3' => {
'title' => 'Parent-3',
'parentid' => '-1'
},
'1' => {
'children' => {
'11' => {
'title' => 'child-1',
},
'5' => {
'children' => {
'8' => {
'title' => 'first child of child-2',
},
'13' => {
'title' => 'second child of child-2',
}
},
'title' => 'child-2',
}
},
'title' => 'Parent-1',
'parentid' => '-1'
},
'2' => {
'title' => 'Parent-2',
'parentid' => '-1'
},
'4' => {
'title' => 'Parent-4',
'parentid' => '-1'
},
};
我使用了以下功能:
sub Options {
my $hash = shift;
my $options = '';
my $iter; $iter = sub {
my $hash = shift;
my $indent = shift || '';
foreach my $k (sort {$a <=> $b} keys %{$hash}) {
my $v = $hash->{$k};
if($v->{parentid} eq '-1'){
$options .= $v->{title} ."-parent\n";
}else{
$options .= $v->{title} . "," ;
}
if ($v->{children}){
$iter->($v->{children}, $indent . "");
}
}
chop($options);
$options .= "\n";
};
$iter->($hash);
return $options;
}
这里它返回一个用逗号分隔的字符串,但我需要某种数据结构,以便能够找到每个键的所有子项(以哈希引用或数组的形式),例如:
Parent-1 -> [child-1,child-2, first child of child-2, second child of child-2]
Parent-2
Parent-3
Parent-4
任何人都可以帮助我吗?提前致谢。
【问题讨论】:
-
您能否为上述结构提供exact所需的输出?
-
实际上哈希键 1,2,3,4 是显示顺序,我想创建一个哈希引用或数组,其键将是标题,根据该标题,我想要所有孩子,以便我可以通过该数组或哈希引用到我的模板并比较每个标题并获取所有子项并将它们显示在我的页面上。
-
你能不能把
$options换成一个数组(比如@descendants),然后把$options .= xxx改成push @descendants, xxx。更改其他几个地方以使用数组而不是标量 / 这为您提供了每个顶级项目的后代的数组。
标签: html perl validation email hashref