![](/img/trans.png)
[英]fetch a single postgres record as an associative array without using while loop
[英]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循环。
谢谢。
php中有一个名为array_walk_recursive()
的函数,您可以在这里找到文档:
http://www.php.net/manual/zh/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 ]);
您也可以使用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;
});
希望能有所帮助
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.