Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/260.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 删除特定id的数组元素_Php_Arrays - Fatal编程技术网

Php 删除特定id的数组元素

Php 删除特定id的数组元素,php,arrays,Php,Arrays,我在变量中得到的id类似于$id=2 比如: $count_id=$request->get('count_id') 从一个函数中,我得到一个数组,如下所示: 比如:$results=get_experiance() 我的问题是,当我在$id=2中获取值时,结果应该是这样的: [0] => stdClass Object ( [id] => 1 [A] => a [B] => b

我在变量中得到的id类似于
$id=2

比如: $count_id=$request->get('count_id')

从一个函数中,我得到一个
数组
,如下所示: 比如:$results=get_experiance()

我的问题是,当我在
$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从获取数组中删除记录。如何实现这一点?任何人都可以用最简单的方法吗???

您可以这样做:

未设置($array[$id])

$array
是数组中所有元素都包含的主变量


$id
是索引

您可以使用
数组过滤器
。如果不想保留现有密钥,也可以使用
array\u value

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

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

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


Doc:,

只需取消设置该键,就像您的数组名是$arr,并且您的键是$key中的2一样,然后写入unset($arr[$key])更改函数以将
id
字段的值用作它返回的数组中的键。在那之后,为了达到你的目标。一个简单的foreach和if应该足够了,如果找到了,就使用unset。这是如何回答问题的?问题被更新了。当时有人说变量包含索引。现在更新了在循环中获取Id等。无论如何,我的坏消息
$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;
});