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

删除特定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条)

报告相同问题?