dongxing7318 2018-01-16 18:33
浏览 6
已采纳

如何从数组php中删除一个值

Hello, I have this code and I want to correct it because it deletes all same value and I want to delete one value

            $rows = "944,1001,1001,3946";
            $sesto = explode(",",$rows);
            $arr = array_diff($sesto,array(1001));
            $comma_separated = implode(",", $arr);
            echo $comma_separated;

i want to be 944,1001,3946

  • 写回答

3条回答 默认 最新

  • dqve65954 2018-01-16 18:38
    关注

    You can use array_search to find the index of the first match and then use array_splice to remove it:

    $rows = "944,1001,1001,3946";
    $arr = explode(",",$rows);
    array_splice($arr, array_search(1001, $arr), 1);
    $comma_separated = implode(",", $arr);
    echo $comma_separated;
    

    Note that this assumes that the element exists in the array. If you try to delete an element that doesn't exist it will delete the first element instead. If you do not want that behaviour use this to make sure it found an element before deleting:

    $rows = "944,1001,1001,3946";
    $arr = explode(",",$rows);
    
    $index = array_search(1001, $arr);
    if ( $index !== false ) 
        array_splice($arr, $index, 1);
    
    $comma_separated = implode(",", $arr);
    echo $comma_separated;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 请问如何在openpcdet上对KITTI数据集的测试集进行结果评估?
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路
  • ¥15 phython读取excel表格报错 ^7个 SyntaxError: invalid syntax 语句报错