2012-03-23 189 views
0

我有for cycle有我創造的名字從名單中的數組,我需要做的就是刪除重複值,然後我得到這個數組:刪除重複的元素

陣列([0] =>託德[1] =>管理[2] => TOD)

$c=count($_SESSION['cart']); 

$list_array = array(); 

    for($i=0;$i<$c;$i++){ 
    $id=$_SESSION['list'][$i]['id']; 
    $person=get_person($id); 

    $list_array[] = $person; 
} 

回答

2

使用array_unique,它返回沒有重複值的新數組。

$input = array("a" => "green", "red", "b" => "green", "blue", "red"); 
$result = array_unique($input); 

輸出

Array 
(
    [a] => green 
    [0] => red 
    [1] => blue 
) 

Check it out here.

但是,你需要移動$list_arrayfor循環之外,並使用你的條件語句等,使得陣列,

$c=count($_SESSION['cart']); 

// if this is in the loop, it will get overwritten 
$list_array = array(); 

for($i=0;$i<$c;$i++){ 
    $id=$_SESSION['list'][$i]['id']; 
    $person=get_person($id); 

    // originally, you had $users_array in in_array and array_push 
    if(!in_array($person, $list_array)) 
     $list_array[] = $person; 

} 
+0

也指這樣的:[PHP :: array_unique爲內部陣列陣列(http://stackoverflow.com/questions/5211900/php-array-unique-for-arrays-inside - 陣列) – Panagiotis 2012-03-23 15:10:37

+0

我試圖使用此之前,但仍然獲得重複的值 – darius 2012-03-23 15:13:16

+0

如果我添加[0]我只得到名字的第一個字母 – darius 2012-03-23 15:21:40

0

in_array在傳遞數組時檢查字符串。與array_unique一樣 - 它不打算檢查多維數組。這樣一個修補程序將是

$person=get_person($id)[0]; 
+0

只要OP有PHP 5.4 – Josh 2012-03-23 15:22:50

+0

這會導致一個錯誤.. get_person是一個簡單的函數,用mysql查詢然後通過週期來收集結果。 'function get_person($ id){ \t \t $ result = mysql_query(「select person from list where id = $ id」); \t \t mysql_set_charset(「UTF8」); \t \t $ row = mysql_fetch_array($ result); \t \t return $ row ['person']; \t}' – darius 2012-03-23 15:22:57

+0

'return $ row ['person'] [0];'then?我的意思是,如果你推送的單個$ person等於'Array([0] => Tod)',那麼顯然你不能期望列表被清理和正確檢查 – 2012-03-23 15:26:04