2011-03-05 189 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