删除重复元素

时间:2012-03-23 15:05:06

标签: php arrays

我有for cycle并且在那里我从列表中创建了一个名称数组,我需要做的是删除重复值,然后我得到这个数组:

数组([0] => Tod [1] => Admin [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 个答案:

答案 0 :(得分: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_array 移到for循环的之外,并在您的条件中使用该数组,

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

}

答案 1 :(得分:0)

在传递数组时,

in_array检查字符串。与array_unique相同 - 它不打算检查多维数组。所以修补程序将是

$person=get_person($id)[0];
相关问题