帮助理解PHP代码到C#
问题描述:
我是一个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#中转换上述代码?我真的很感激。
答
PHP(和一些其他语言)使用字典(关联数组)作为通用数据结构。在PHP中,array()
创建可以嵌套的无类型字典结构。
在C#中,不会使用字典来编写相同的代码,而是使用强类型的数据结构。这意味着您将创建单独的类来表示这些数据结构,并使用成员变量而不是PHP代码中关联数组的键 - 值对。
答
您可以使用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
感谢您的解释Konrad。你能帮我翻译C#吗?我不是专家,但我可以尝试给出的例子。 – user342944 2010-05-17 11:06:10
这样的事情? http://csharptutorial.com/blog/use-strongly-typed-generics-dictionary-data-structure-to-lookup-constants/ – user342944 2010-05-17 11:10:20