2010-05-17 67 views
0

我是一個C#人,並從一個網站得到了這個邏輯到PHP。需要在C#中實現相同的功能。幫助理解PHP代碼到C#

$items = array(); 
while($row = mysql_fetch_assoc($query)) 
{ 
//parent id 
$pkey = $row['parent_id']; 
//child id 
$ckey = $row['category_id']; 
//store this 
$items[$pkey]['children'][$ckey] = $row['categoryname']; 
} 
//create our list 
$first = true; 
//create our list 
createList($items, $first); 

function createList($array, $first) 
{ 
//we need access to the original array 
global $items; 
//first is a flag on whether or not this is the first item in the array 
//we use this flag so that you don't need to initially call the function using createList($array[0]['children']) 
if($first){ 
    $array = $array[0]['children']; 
} 
echo "<ol>\n"; 
foreach($array as $key => $value){ 
    echo "<li>{$value}"; 
    //if this item does have children, display them 
    if(isset($items[$key]['children'])){ 
    echo "\n"; 
    createList($items[$key]['children'], false); //set $first to false! 
    } 
    echo "</li>\n"; 
} 
echo "</ol>\n"; 

}

在上述最後一行是一個3維陣列或哈希表?它看起來像一個哈希表的原因[$ pkey] ['children'] [$ ckey]正在竊聽我..

任何人都可以在C#中轉換上述代碼?我真的很感激。

回答

2

PHP(和一些其他語言)使用字典(關聯數組)作爲通用數據結構。在PHP中,array()創建可以嵌套的無類型字典結構。

在C#中,不會使用字典來編寫相同的代碼,而是使用強類型的數據結構。這意味着您將創建單獨的類來表示這些數據結構,並使用成員變量而不是PHP代碼中關聯數組的鍵 - 值對。

+0

感謝您的解釋Konrad。你能幫我翻譯C#嗎?我不是專家,但我可以嘗試給出的例子。 – user342944 2010-05-17 11:06:10

+0

這樣的事情? http://csharptutorial.com/blog/use-strongly-typed-generics-dictionary-data-structure-to-lookup-constants/ – user342944 2010-05-17 11:10:20

0

您可以使用Dictionary<string, Dictionary<string, string>>結構對此數據建模。代碼的第一部分,填充結構會這樣:

Dictionary<string, Dictionary<string, string>> items 
        = new Dictionary<string, Dictionary<string, string>>(); 
string pkey, ckey; 

foreach (Dictionary<string, string> row in fetch(query)) 
{ 
    //parent id 
    pkey = row["parent_id"]; 

    //child id 
    ckey = ""; 
    if (row.ContainsKey("category_id")) ckey = row["category_id"]; 

    //store this 
    Dictionary<string, string> children; 
    if (items.ContainsKey(pkey)) children = items[pkey]; 
    else children = new Dictionary<string, string>(); 

    if (ckey.Length != 0) children[ckey] = row["categoryname"]; 

    items[pkey] = children; 
} 
+0

因此,每個循環都填充每個項目的孩子? hummm – user342944 2010-05-17 12:44:14