2016-01-13 50 views
0

我返回一個數組就像下面的簡單的例子,當刪除重複項:PHP MySQL的一個一對多的數據庫返回輸出到HTML表

0 => 
    object(stdClass)[9] 
     public 'crew_chief' => string 'Alan' (length=4) 
     public 'location' => string '1a' (length=2) 
    1 => 
    object(stdClass)[22] 
     public 'crew_chief' => string 'Alan' (length=4) 
     public 'location' => string '2a' (length=2) 

我想我的循環在我的數組和除去某些重複的信息(在這種情況下,「阿蘭」)

所需的輸出看起來像下面的HTML表格行<tr>

Alan 
1a 
2a 

我曾嘗試:

foreach($records as $r) { 
    <tr> 
    <td> 
     $r->crew_chief; 
    </td> 

    <td> 
     $r->location . <br />; 
    </td> 
    </tr> 
} 
+1

爲什麼不直接在您的查詢中進行呢?你想爲此使用PHP的任何特定原因? –

+0

@Fred如果您擁有足夠的服務器內存,則使用PHP處理數據比直接使用SQL更快。我發現運行一個廣泛的查詢,然後使用PHP對結果進行排序比運行多個更精確的查詢要快得多。這也不是一個小小的差異。我已經看到1小時運行變成了10秒運行。 – Typel

+0

你可以指點我一些很好的文檔來解釋如何編寫一個sql查詢來完成這個任務。我不確定我完全理解這是如何工作的,當我使用多個表並刪除重複的「Alan」(一對多關係) – user1040259

回答

3

做到這一點,最好的辦法是從MySQL查詢直接使用語句SELECT DISTINCT col FROM table WHERE data='data' GROUP BY row

但是,如果你想使用你的代碼,你將能夠在一個單獨的存儲每個名字要做到這一點數組array['Alan'] = 'data'並重新打開該數組以輸出數據,導致索引Alan已存在並被覆蓋。

1

無論何時想要消除數組中的重複條目,您都可以簡單地遍歷數組,將每個元素放入一個新數組中,該數組使用重複索引的值作爲新數組的索引。這樣一來,重複就會自然消失,因爲它們只是彼此重寫。例如,以此爲例。這考慮到你有一組對象,但是這個概念對於陣列也是一樣的。

$condensed = array(); 
foreach($records as $index=>$r) { 
    $condensed[$r->crew_chief] = $r; 
    // optionally, you can save the original index, so that you can rebuild 
    // the original array with the same original index structure again 
    $condensed[$r->crew_chief]['original_index'] = $index; 
    } 

// that eliminated all the duplicates, but if you want your array to 
// have the same structure (with same indexes) as the original, let's 
// use our saved indexes above to rebuild things as they were 
$deduped = array(); 
foreach($condensed as $c) { 
    $deduped[$c['original_index']] = $c; 
    unset($deduped[$c['original_index']]['original_index']); // be clean! 
    } 

// don't forget memory management 
unset($condensed); 
相關問題