简体   繁体   中英

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.

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.

Thanks.

there's a function in php called array_walk_recursive() you can find the documentation here:

http://www.php.net/manual/en/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:

$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. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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