如何在不使用 for 循环的情况下删除数组中的记录


How to delete a record in array without using for loop

我有这个数组集合,它的格式是这样的:

$collection = array(
    '0' => array(
        'user_id' => 12345
        'name' => 'test'
    ),
    '1' => array(
        'user_id' => 6789
        'name' => 'test2'
    ),
)

我的问题是我不想创建一个 for 循环来搜索 id:6789。

目前,我正在做的是这样的:

$user_id = 6789
foreach($collection as $key => $collect)
{
    if($collect['user_id'] == $user_id)
    {
         unset($collection[$key]);
    }
}

我只是想问是否有一种更有效的方法来删除数据而不是执行 for 循环。

谢谢。

您也可以使用 array_filter 来完成此操作。鉴于您的意见:

$collection = array(
    '0' => array(
        'user_id' => 12345,
        'name' => 'test',
    ),
    '1' => array(
        'user_id' => 6789,
        'name' => 'test2',
    ),
);
$user_id = 6789;

您可以使用:

$new_collection = array_filter( $collection, function($item) use ($user_id) {
  return $item['user_id'] != $user_id;
});

希望有帮助

PHP 中有一个名为 array_walk_recursive() 你可以在这里找到文档:

http://www.php.net/manual/en/function.array-walk-recursive.php

我不确定它是否比使用循环更有效,但它应该按照您的要求做

我想不出更好的方法来查找密钥,因为这些项目存储在多维数组中。但是,如果您可以通过将user_id放在键中来以不同的方式构建初始数组,例如:

$collection = array(
    '12345' => array(
        'user_id' => 12345
        'name' => 'test'
    ),
    '6789' => array(
        'user_id' => 6789
        'name' => 'test2'
    ),
)

然后你可以做

$user_id = 6789;
unset($collection[$user_id ]);