2014-10-28 62 views
0

我希望有人提供一個想法,我如何做到這一點。一個數組的循環邏輯,唯一的ID

我有這樣的數據:現在

0 -> id=1 other_id = 2 
1 -> id=1 other_id = 3 
2 -> id=1 other_id = 4 
3 -> id=2 other_id = 7 
4 -> id=2 other_id = 5 

,在我的循環,我想推,獨特的ID並連接其它ID數據,因此其結果將是:

0-> id=1 other_ids = 2,3,4 
1-> id=2 other_ids = 7,5 

我考慮使用臨時變量但不能完成數據結構。

順便說一下,我使用的codeigniter,結果是從模型,我想通過PHP在控制器中操縱它。

回答

0

我希望幫助您

第1步:創建類

public class Person 
    { 
     public int id { get; set; } 
     public int other_id { get; set; } 
    } 

第1步:這個代碼將有助於你

string output = string.Empty; 

     List<Person> lst = new List<Person>(); 
     lst.Add(new Person(){ id= 1, other_id = 2}); 
     lst.Add(new Person(){ id= 1, other_id = 3}); 
     lst.Add(new Person(){ id= 1, other_id = 4}); 
     lst.Add(new Person(){ id= 2, other_id = 7}); 
     lst.Add(new Person(){ id= 2, other_id =5 }); 

     List<int> idlst = new List<int>(); 
     idlst = lst.Select(x => x.id).Distinct().ToList(); 


     foreach (int _id in idlst) 
     { 
      List<int> other_idlist = lst.Where(x => x.id == _id).Select(x=> x.other_id).ToList(); 
      output += string.Format("id={0} other_ids = {1}", _id, string.Join(",", other_idlist)) + Environment.NewLine; 
     } 

     MessageBox.Show(output); 
+0

感謝您的輸入。我錯過了標記我的問題爲PHP。我檢查你的代碼,我會看看如果我可以將其轉換爲PHP。 – derping 2014-10-28 08:56:55