删除特定id的数组元素

时间:2018-06-19 07:42:21

标签: php arrays

我在变量

中获得了$id=2的ID

像: $ count_id = $请求 - >获得( 'count_id');

从一个函数我得到array如下所示:    像:$结果= 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
        )

我的问题是,当我得到$id=2中的值时,结果应该是这样的:

[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
        )

表示我想根据id删除get数组中的记录。我怎样才能实现这一点,谁能有最简单的方法?

2 个答案:

答案 0 :(得分:4)

您可以使用array_filter。如果您不想保留现有密钥,也可以使用array_values

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

echo "<pre>";
print_r( $result );
echo "</pre>";

这将返回:

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
        )

)

如果您不想要新变量,可以将数组覆盖为

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

文档:array_filter()array_values()

答案 1 :(得分:-3)

你可以这样做:

未设置($阵列[$ ID]);

$array是数组的所有元素都包含

的主要变量

$id是索引