php从数组中删除特定值
我有一个数组php从数组中删除特定值,php,arrays,Php,Arrays,我有一个数组$products,看起来像这样 Array ( [services] => Array ( [0] => Array ( [id] => 1 [icon] => bus.png [name] => Web Development
$products
,看起来像这样
Array
(
[services] => Array
(
[0] => Array
(
[id] => 1
[icon] => bus.png
[name] => Web Development
[cost] => 500
)
[1] => Array
(
[id] => 4
[icon] => icon.png
[name] => Icon design
[cost] => 300
)
)
)
我试图删除与[id]=>1
匹配的数组部分,为此我使用以下代码
$key = array_search('1', $products);
unset($products['services'][$key]);
然而,它不工作,我也没有得到任何错误。
我做错了什么?这应该适合您:
$key = array_search('1', $products["services"]);
//^^^^^^^^^^^^ See here i search in this array
unset($products['services'][$key]);
print_r($products);
输出:
Array ( [services] => Array ( [1] => Array ( [id] => 4 [icon] => icon.png [name] => Icon design [cost] => 300 ) ) )
如果要对数组重新编制索引,使其重新以0开头,则可以执行以下操作:
$products["services"] = array_values($products["services"]);
然后得到输出:
Array ( [services] => Array ( [0] => Array ( [id] => 4 [icon] => icon.png [name] => Icon design [cost] => 300 ) ) )
//^^^ See here starts again with 0
这应该适合您:
$key = array_search('1', $products["services"]);
//^^^^^^^^^^^^ See here i search in this array
unset($products['services'][$key]);
print_r($products);
输出:
Array ( [services] => Array ( [1] => Array ( [id] => 4 [icon] => icon.png [name] => Icon design [cost] => 300 ) ) )
如果要对数组重新编制索引,使其重新以0开头,则可以执行以下操作:
$products["services"] = array_values($products["services"]);
然后得到输出:
Array ( [services] => Array ( [0] => Array ( [id] => 4 [icon] => icon.png [name] => Icon design [cost] => 300 ) ) )
//^^^ See here starts again with 0
这将循环通过
$products['services']
并删除'id'
键的值为1的数组<代码>数组\u值只需再次从0重新索引数组
foreach($products['services'] as $key => $service)
{
if($product['id'] == 1)
{
unset($products['services'][$key]);
array_values($products['services']);
break;
}
}
这将循环通过
$products['services']
并删除'id'
键的值为1的数组<代码>数组\u值只需再次从0重新索引数组
foreach($products['services'] as $key => $service)
{
if($product['id'] == 1)
{
unset($products['services'][$key]);
array_values($products['services']);
break;
}
}
您是只想从该子阵列中删除[id]=>1,还是只想从整个父阵列中删除[id]=>1(在本例中为键0)?foreach是一种go@edwardmp我想删除整个父数组(在本例中为0键),您只想从该子数组中删除[id]=>1,还是要删除整个父数组(在本例中为0键)?foreach是通往go@edwardmp我想删除整个父数组(在本例中为键0)