C# 帮助理解C语言中的PHP代码#
我是一个C#人,从一个网站上把这个逻辑输入php。需要在C#中实现同样的功能C# 帮助理解C语言中的PHP代码#,c#,php,C#,Php,我是一个C#人,从一个网站上把这个逻辑输入php。需要在C#中实现同样的功能 $items=array(); while($row=mysql\u fetch\u assoc($query)) { //父id $pkey=$row['parent_id']; //儿童id $ckey=$row['category_id']; //储存这个 $items[$pkey]['children'][$ckey]=$row['categoryname']; } //创建我们的列表 $first=true;
$items=array();
while($row=mysql\u fetch\u assoc($query))
{
//父id
$pkey=$row['parent_id'];
//儿童id
$ckey=$row['category_id'];
//储存这个
$items[$pkey]['children'][$ckey]=$row['categoryname'];
}
//创建我们的列表
$first=true;
//创建我们的列表
createList($items,$first);
函数createList($array,$first)
{
//我们需要访问原始阵列
全球$项目;
//first是一个关于这是否是数组中的第一项的标志
//我们使用这个标志,这样您就不需要首先使用createList($array[0]['children']调用函数)
如果($第一){
$array=$array[0]['children'];
}
回音“\n”;
foreach($key=>$value的数组){
回声“{$value}”;
//如果此项目确实有子项,请显示它们
如果(设置($items[$key]['children'])){
回音“\n”;
createList($items[$key]['children',false);//将$first设置为false!
}
回声“ \n”;
}
回音“\n”;
}
在上面的最后一行中,它是三维数组还是哈希表?这看起来像是一个哈希表,因为[$pkey][$children'][$ckey]在烦我
有人能用C#转换上面的代码吗?非常感谢。PHP(和其他一些语言)使用字典(关联数组)作为通用数据结构。在PHP中,array()
创建一个可以嵌套的非类型化字典结构
在C#中,相同的代码不会使用字典编写,而是使用强类型数据结构。这意味着您将创建单独的类来表示这些数据结构,使用成员变量而不是PHP代码中关联数组的键值对。您可以使用
字典
结构对这些数据建模。填充结构的第一部分代码如下所示:
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;
}
字典项
=新字典();
字符串pkey,ckey;
foreach(获取(查询)中的字典行)
{
//父id
pkey=行[“父项id”];
//儿童id
ckey=“”;
if(row.ContainsKey(“category_id”))ckey=row[“category_id”];
//储存这个
字典儿童;
if(items.ContainsKey(pkey))children=items[pkey];
else children=新字典();
如果(ckey.Length!=0)子项[ckey]=row[“categoryname”];
项目[pkey]=子项;
}
感谢康拉德的解释。你能帮我用C语言翻译吗?虽然我不是专家,但如果举个例子,我可以试试。像这样的?那么for each的整个循环就是填充每个项目的子项?哼哼
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;
}