C # içine PHP kodu anlamak için yardım

2 Cevap

Ben bir C # adam ve bir web sitesinden php içine bu mantık var. C # aynı uygulamak gerekir.

$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";

}

Yukarıdaki son satırda bir 3 boyutlu dizi ya hashtable nedir? o [$ ckey] beni adamcağız onun bir hashtable nedenidir [$ pkey] ['çocuk'] gibi görünüyor ..

Herkes C # yukarıdaki kodu dönüştürebilir miyim? Ben gerçekten takdir ediyorum.

2 Cevap

PHP (ve bazı diğer diller) evrensel veri yapıları olarak sözlüklerinin (ilişkisel diziler) kullanın. PHP, array() iç içe olabilir Türlenmemiş sözlük yapısı oluşturur.

C #, aynı kod sözlükleri değil kesinlikle yazdığınız veri yapıları kullanılarak yazılmış olmaz. Yani yerine PHP kodu birleşmeli diziler anahtar-değer çiftleri üye değişkenleri ile, bu veri yapılarını temsil etmek için tek tek sınıfları yaratacak demektir.

Bir Dictionary<string, Dictionary<string, string>> yapısı ile bu veri modeli olabilir. Kodun ilk bölümü, bu yapı böyle gider doldurur:

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;
}