简体   繁体   English

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

[英]How to delete a record in array without using for loop

I have this array collection which is formatted in this way: 我有此数组集合,其格式是这样的:

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

My problem is that I don't want to create a for loop to search for the id:6789. 我的问题是我不想创建for循环来搜索id:6789。

Currently, what I'm doing is this: 目前,我正在做的是:

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

I just want to ask if there is a much efficient way of deleting the data instead of doing a for loop. 我只想问一下是否有一种有效的方法来删除数据,而不是执行for循环。

Thanks. 谢谢。

there's a function in php called array_walk_recursive() you can find the documentation here: php中有一个名为array_walk_recursive()的函数,您可以在这里找到文档:

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

im not sure if it will be more efficient than using loops but it should do what your asking 我不确定它是否比使用循环更有效,但它应该按照您的要求进行

I can't think of a better way of finding the key as the items are stored in a multi-dimensional array. 由于项目存储在多维数组中,我想不出找到密钥的更好方法。 However if you could build your initial array differently by putting the user_id in the key eg: 但是,如果您可以通过将user_id放在键中来不同地构建初始数组,例如:

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

Then you can just do 那你就可以做

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

You can also use array_filter to accomplish this. 您也可以使用array_filter完成此操作。 Given your input of: 根据您的输入:

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

$user_id = 6789;

You can use: 您可以使用:

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

Hope that helps 希望能有所帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM