[英]Removing array key from multidimensional Arrays php
I have this array我有这个数组
$cart= Array(
[0] => Array([id] => 15[price] => 400)
[1] => Array([id] => 12[price] => 400)
)
What i need is to remove array key based on some value, like this我需要的是根据某个值删除数组键,就像这样
$value = 15;
Value is 15 is just example i need to check array and remove if that value exist in ID?值为 15 只是示例,我需要检查数组并删除 ID 中是否存在该值?
array_filter
is great for removing things you don't want from arrays. array_filter
非常适合从数组中删除你不想要的东西。
$cart = array_filter($cart, function($x) { return $x['id'] != 15; });
If you want to use a variable to determine which id to remove rather than including it in the array_filter
callback, you can use
your variable in the function like this:如果您想使用变量来确定要删除的 id 而不是将其包含在
array_filter
回调中,您可以在函数中use
您的变量,如下所示:
$value = 15;
$cart = array_filter($cart, function($x) use ($value) { return $x['id'] != $value; });
There are a lot of weird array functions in PHP, but many of these requests are solved with very simple foreach loops... PHP 中有很多奇怪的数组函数,但是很多这些请求都是通过非常简单的 foreach 循环来解决的……
$value = 15;
foreach ($cart as $i => $v) {
if ($v['id'] == $value) {
unset($cart[$i]);
}
}
If $value is not in the array at all, nothing will happen.如果 $value 根本不在数组中,则什么都不会发生。 If $value is in the array, the entire index will be deleted (unset).
如果 $value 在数组中,则整个索引将被删除(未设置)。
you can use:你可以使用:
foreach($array as $key => $item) {
if ($item['id'] === $value) {
unset($array[$key]);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.