考虑此数组:
$userBookmarks = [
[
"id": 10000,
"dateAdded": 1552127606
],
[
"id": 20000,
"dateAdded": 1552127610
],
[
"id": 30000,
"dateAdded": 1552127614
]
]
假设我知道ID为10000,并且要删除id
值为10000的子数组,最有效的方法是删除整个子数组并保留以下内容:
$userBookmarks = [
[
"id": 20000,
"dateAdded": 1552127610
],
[
"id": 30000,
"dateAdded": 1552127614
]
]
我的“最近”尝试:
for( $i = 0; $i < count( $userBookmarks ); $i++ ) {
$currentBookmark = $userBookmarks[ $i ];
if( $currentBookmark['id'] == $newBookmarkID ) {
unset( $currentBookmark );
break;
} else {
$userBookmarks[] = $newBookmark;
}
}
但实际上什么也没做...
答案 0 :(得分:0)
一个简单的解决方法。
您需要unset()
对子数组的原始引用。
更改:
unset( $currentBookmark );
收件人:
unset( $userBookmarks[ $i ] );
“功能性”替代方案如下所示:
$userBookmarks = [
["id" => 10000, "dateAdded" => 1552127606],
["id" => 20000, "dateAdded" => 1552127610],
["id" => 30000, "dateAdded" => 1552127614]
];
$newBookmarkID = 10000;
$userBookmarks = array_filter($userBookmarks, function ($v) use ($newBookmarkID) {
return $v['id'] != $newBookmarkID;
});
var_export($userBookmarks);