![](/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.