doutizhou5312 2018-06-19 07:42
浏览 233
已采纳

删除特定id的数组元素

I am getting id like $id=2 in a variable

like: $count_id=$request->get('count_id');

and from a function i am getting a array like given below: like:$results=get_experiance();

    [0] => stdClass Object
        (
            [id] => 1
            [A] => a
            [B] => b
            [C] => c
            [D] => d
        )

    [1] => stdClass Object
        (
            [id] => 2
            [A] => w
            [B] => s
            [C] => d
            [D] => a
        )

    [2] => stdClass Object
        (
            [id] => 3
            [A] => r
            [B] => e
            [C] => f
            [D] => v
        )

My question is that when i am getting the value in $id=2 result should be like that :

[0] => stdClass Object
        (
            [id] => 1
            [A] => a
            [B] => b
            [C] => c
            [D] => d
        )
[1] => stdClass Object
        (
            [id] => 3
            [A] => r
            [B] => e
            [C] => f
            [D] => v
        )

Means i want to delete the record from the getting array based on id. How can i achieve this can anyone have simplest way ??

  • 写回答

2条回答 默认 最新

  • dongquanjie9328 2018-06-19 07:47
    关注

    You can use array_filter. You can also use array_values if you dont want to retain the existing keys.

    $arr = your array
    $toRemove = "2";
    $result = array_filter($arr, function($o) use ($toRemove){
        return $toRemove != $o->id;
    });
    
    echo "<pre>";
    print_r( $result );
    echo "</pre>";
    

    This will return:

    Array
    (
        [0] => stdClass Object
            (
                [id] => 1
                [A] => a
                [B] => b
                [C] => c
                [D] => d
            )
    
        [2] => stdClass Object
            (
                [id] => 3
                [A] => r
                [B] => e
                [C] => f
                [D] => v
            )
    
    )
    

    If you dont want a new variable, you can just overide the array as

    $arr = array_filter($arr, function($o) use ($toRemove){
        return $toRemove != $o->id;
    });
    

    Doc: array_filter(), array_values()

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 请问为什么我配置IPsec后PC1 ping不通 PC2,抓包出来数据包也并没有被加密
  • ¥200 求博主教我搞定neo4j简易问答系统,有偿
  • ¥15 nginx的使用与作用
  • ¥100 关于#VijeoCitect#的问题,如何解决?(标签-ar|关键词-数据类型)
  • ¥15 一个矿井排水监控系统的plc梯形图,求各程序段都是什么意思
  • ¥15 ensp路由器启动不了一直报#
  • ¥50 安卓10如何在没有root权限的情况下设置开机自动启动指定app?
  • ¥15 ats2837 spi2从机的代码
  • ¥200 wsl2 vllm qwen1.5部署问题
  • ¥100 有偿求数字经济对经贸的影响机制的一个数学模型,弄不出来已经快要碎掉了