【发布时间】:2011-07-09 06:37:15
【问题描述】:
我有这个 php 代码:
$lines = file("data.csv");
$nested = array();
$links = array();
// first, create a structure that contains the connections between elements
foreach ($lines as $line) {
list($child, $parent) = explode(",", $line);
if (trim($child) == trim($parent)) {
$nested[$parent] = null;
} else {
// add it to the children of parent
$links[$parent][] = $child;
}
}
function process(&$arr) {
global $links;
foreach ($arr as $key => $value) {
// no more children => stop recursion
if (!array_key_exists($key, $links)) {
$array[$key] = null;
continue;
}
// insert its children
$arr[$key] = array_flip($links[$key]);
// recurse down
process($arr[$key]);
}
}
function print_html($multi_dimensional_array)
{
$m = $multi_dimensional_array;
$keys = array();
foreach($m as $key=>$value) {
$keys[] = $key;
}
$i = 0;
while($i < count($multi_dimensional_array)) {
echo '<li><a href="#">'.$keys[$i].'</a>';
if(is_array($multi_dimensional_array[$keys[$i]])) {
echo '<ul>';
print_html($multi_dimensional_array[$keys[$i]]);
echo '</ul>';
}
echo '</li>';
$i++;
}
}
process($nested);
print_html($nested);
data.csv 格式为 (value,parent),例如:
one,one
two,two
three,three
sub_one,one
sub_one2,one
sub_two,two
sub_two2,two
sub_two3,two
sub_three,three
sub_sub_one,sub_one
sub_sub_one2,sub_one
基本上,这个 PHP 代码所做的就是创建一个多维数组,其中包含作为键的父名称和作为值的子名称,如果一个子名称还包含子子项,那么它将是一个包含子键等的键...然后它将为该数组打印一个 html 格式的列表。
我如何使用 C# 来完成这段 php 代码的工作?
【问题讨论】:
-
我认为你需要先自己尝试一下,看看你有什么问题。该站点不会为您编写所有代码。开始做,面对问题。如果问题足够具体且措辞恰当,您将在此处获得帮助
-
同意Dyppl——这两种语言不同,有不同的优势。如果您自己不努力尝试这项任务,您将是对自己的伤害。
-
为了给你一个开始的地方,我建议你看看
Dictionary<TKey, TValue>(msdn.microsoft.com/en-us/library/xfhwa508.aspx)。
标签: c# php arrays recursion multidimensional-array