I am a C# guy and got this logic into php from a website. Need to implement the same in 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";
}
In the above last line is it a 3 dimensional array or hashtable? it looks like its a hashtable cause [$pkey]['children'][$ckey] is bugging me..
Can anyone convert the above code in C#? I would really appreciate.
PHP (and some other languages) use dictionaries (associative arrays) as universal data structures. In PHP, array()
creates an untyped dictionary structure that can be nested.
In C#, the same code would not be written using dictionaries but rather strongly-typed data structures. That means you would create individual classes to represent these data structures, with member variables instead of the key-value pairs of the associative arrays in the PHP code.
You could model this data with a Dictionary<string, Dictionary<string, string>>
structure. The first part of the code, that fills up the structure would go like this:
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;
}
精彩评论