dtp0760 2012-03-23 15:05
浏览 61
已采纳

删除重复元素

I have for cycle and there I create an array of names from the list, and what I need to do is remove duplicate values, then I get this array:

Array ( [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条回答 默认 最新

  • dsnnvpobaljihv3490 2012-03-23 15:07
    关注

    Use array_unique, which returns a new array without duplicate values.

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

    Outputs

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

    Check it out here.

    However, you need to move $list_array outside of your for loop, and use that array in your conditionals like so,

    $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条)

报告相同问题?

悬赏问题

  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line