php从数组中删除特定值

时间:2015-01-18 13:38:56

标签: php arrays

我有一个类似

的数组$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]);

然而它不起作用,我也没有收到任何错误。 我做错了什么?

2 个答案:

答案 0 :(得分:3)

这应该适合你:

$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

答案 1 :(得分:2)

这将循环遍历$products['services']并删除'id'键值为1的数组。array_values只是再次从0重新索引数组。

foreach($products['services'] as $key => $service)
{
    if($product['id'] == 1)
    {
        unset($products['services'][$key]);
        array_values($products['services']);
        break;
    }
}