2011-02-22 111 views
-2
<?php 

$list = array(
    array(
     'id' => '1', 
     'pid' => '2', 
     'value' => 'Value Foo 1', 
    ), 
    array(
     'id' => '2', 
     'pid' => '6', 
     'value' => 'Value Foo 2', 
    ), 
    array(
     'id' => '3', 
     'pid' => '5', 
     'value' => 'Value Foo 3', 
    ), 
    array(
     'id' => '4', 
     'pid' => '2', 
     'value' => 'Value Foo 4', 
    ), 
    array(
     'id' => '5', 
     'pid' => '0', 
     'value' => 'Value Foo 5', 
    ), 
    array(
     'id' => '6', 
     'pid' => '0', 
     'value' => 'Value Foo 6', 
    ), 
    array(
     'id' => '7', 
     'pid' => '6', 
     'value' => 'Value Foo 7', 
    ), 
    array(
     'id' => '8', 
     'pid' => '2', 
     'value' => 'Value Foo 8', 
    ), 
    array(
     'id' => '9', 
     'pid' => '5', 
     'value' => 'Value Foo 9', 
    ), 
); 

// 
// Creating a lookup array 
// 
$lookup = array(); 
foreach($list as $item) 
{ 
    $item['children'] = array(); 
    $lookup[$item['id']] = $item; 
} 

// 
// Now build tree. 
// 
$tree = array(); 
foreach($lookup as $id => $foo) 
{ 
    $item = &$lookup[$id]; 
    if($item['pid'] == 0) 
    { 
     $tree[$id] = &$item; 
    } 
    else if(isset($lookup[$item['pid']])) 
    { 
     $lookup[$item['pid']]['children'][$id] = &$item; 
    } 
    else 
    { 
     $tree['_orphans_'][$id] = &$item; 
    } 
} 

print_r($tree); 
?> 

這是我在C#中如何在PHP腳本轉換爲C#

public class Thing { 
      public String _id; 
      public int Bar; 
      public string _pid; 
    } 
      var items = new[] { 
       new Thing { _id = "item1", _pid = "root", Baz = "a" }, 
       new Thing {_id = "item2", _pid = "item1", Baz= "b" }, 
       new Thing { _id = "item3", _pid = "item1", Baz = "c" }, 
       new Thing { _id = "item4", _pid = "item1", Baz = "d" }, 
       new Thing { _id = "item5", _pid = "item1", Baz = "e" }, 
       new Thing { _id = "item6", _pid = "item1", Baz = "f" } 
       }; 
//Then I create a lookup 
ILookup<string, Thing> lookup = items.ToLookup(i => i._id); 

//here is when I want to create a condition for each item in lookup to search if the _pid is in //the lookup as an item _id 

foreach (IGrouping<string, Thing> item in lookup){ 

//here I dont know how to add a children object to the parent item and add a reference to the //current item 
//this is how Iam doing in php 
if(isset($lookup[$item['_pid']])) { 
$lookup[$item['_pid']]['children'][_id] = &$item; //<-item is passed by reference 
} 

謝謝.. 問候有

+1

需要方式更多上下文。你在做什麼PHP,你在C#中做什麼?代碼與對方有什麼關係? – 2011-02-22 23:39:31

+1

所以你實際上想要將PHP代碼轉換爲C#而不是「將PHP函數傳遞給C#」(無論這意味着什麼)? – 2011-02-22 23:40:40

+0

這個問題並沒有太大的意義。你想**在C#中重寫**這個過程,並且遇到麻煩,或者你是否嘗試執行PHP腳本,然後在單獨的C#程序中使用**結果**? – 2011-02-22 23:41:05

回答

0

更好的使用比匿名對象的真實對象的,除非你知道你在做什麼!

+0

對你之後的內容仍然有點模糊,但是我會轉儲ILookup,只是拿着對象的IList並且使用諸如Where Where查找你想要的東西等方法。 – tommy5dollar 2011-02-23 15:01:05