我希望每个键的所有节点都按哈希引用或数组或类似的键排序,以便我可以根据需要对其进行迭代,因为我必须显示每个键及其所有子项。以下是我的数据结构:
$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
任何人都可以帮助我吗?提前致谢。