2011-03-05 111 views
-3

我有这样的PHP代码:需要帮助PHP转换为C#

$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格式(值,母体),一个例子是:

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代码呢?

+7

我认为你需要先尝试一下自己,并找出你有什么问题。本网站不会为您编写所有代码。开始这样做,面对问题。如果问题的具体情况足够详细,你会在这里得到帮助 – Dyppl 2011-03-05 05:01:03

+1

同意Dyppl - 这两种语言是不同的,有不同的优势。如果你没有努力去亲自尝试这个任务,那么你会对自己造成伤害。 – anon 2011-03-05 05:04:35

+0

为了给你开始的地方,我建议看'Dictionary '(http://msdn.microsoft.com/en-us/library/xfhwa508.aspx)。 – 2011-03-05 05:05:42

回答

0

C#中的数组与PHP中的数组不同。您可能需要实施Composite pattern才能获得所需的数据结构。这只是一小部分任务的正确方向(我认为)。如果您确实最终使用了该模式,请考虑Dictionary<string, TComposite>作为子类型收集的类型。

+0

谢谢,我最终使用Dictionary ,它比使用php更容易。 – nitrkli 2011-03-05 16:04:40