如何从数组中删除特定数量的元素

我有一个函数,它从数组中删除元素:


function remove_from_cart($prod_name,$price,$params,$count)

{


    $cart = array(

    "0"  => array ( 

    'name' => 'Bolognese - Small (26cm)',

    'params' => '',

    'price' => '12'),


    "1"  => array ( 

    'name' => 'Bolognese - Small (26cm)',

    'params' => '',

    'price' => '12')

    );


    $prod_arr = array(

    "name"=> $prod_name,

    "params"=> $params,

    "price" => $price);


    $count  = count( array_keys( $cart, $prod_arr ));


    while(($key = array_search($prod_arr, $cart)) !== false) {unset($cart[$key]);}


    return array('cart' => $cart, 'count' => $count);

}




$rem = remove_from_cart('Bolognese - Small (26cm)', '12', $params, 1);

//here is i want to remove just 1 of 2 elements

如何修改此函数以设置我想从数组中删除的元素数量?


谢谢!


慕斯王
浏览 275回答 1
1回答

函数式编程

您的示例和问题不太清楚,但您可以查看此解决方案:<?phpfunction remove_from_cart($prod_name,$price,$params,$count){&nbsp; &nbsp; $cart = array(&nbsp; &nbsp; "0"&nbsp; => array (&nbsp; &nbsp; 'name' => 'Bolognese - Small (26cm)',&nbsp; &nbsp; 'params' => '',&nbsp; &nbsp; 'price' => '12'),&nbsp; &nbsp; "1"&nbsp; => array (&nbsp; &nbsp; 'name' => 'Bolognese - Small (26cm)',&nbsp; &nbsp; 'params' => '',&nbsp; &nbsp; 'price' => '12'),&nbsp; &nbsp; "2"&nbsp; => array (&nbsp; &nbsp; 'name' => 'Bolognese - Small (26cm)',&nbsp; &nbsp; 'params' => '',&nbsp; &nbsp; 'price' => '12')&nbsp; &nbsp; );&nbsp; &nbsp; $prod_arr = array(&nbsp; &nbsp; "name"=> $prod_name,&nbsp; &nbsp; "params"=> $params,&nbsp; &nbsp; "price" => $price);&nbsp; &nbsp; $i = 0;&nbsp; &nbsp; while(($key = array_search($prod_arr, $cart)) !== false && $i < $count) {unset($cart[$key]); $i++;}&nbsp; &nbsp; return array('cart' => $cart, 'count' => $count);}$params = '';$rem = remove_from_cart('Bolognese - Small (26cm)', '12', $params, 1);var_dump($rem);这将返回两个元素,因为它们是 3 个元素,$count如果传递 2,则传递 1,它将返回 1 个元素:结果为$rem = remove_from_cart('Bolognese - Small (26cm)', '12', $params, 1);:array(2) { ["cart"]=> array(2) { [1]=> array(3) { ["name"]=> string(24) "Bolognese - Small (26cm)" ["params"]=> string(0) "" ["price"]=> string(2) "12" } [2]=> array(3) { ["name"]=> string(24) "Bolognese - Small (26cm)" ["params"]=> string(0) "" ["price"]=> string(2) "12" } } ["count"]=> int(1) }结果为$rem = remove_from_cart('Bolognese - Small (26cm)', '12', $params, 2);:array(2) { ["cart"]=> array(1) { [2]=> array(3) { ["name"]=> string(24) "Bolognese - Small (26cm)" ["params"]=> string(0) "" ["price"]=> string(2) "12" } } ["count"]=> int(2) }
打开App,查看更多内容
随时随地看视频慕课网APP