为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

PHP
慕斯王 2021-12-03 11:02:52
我有一个函数,它从数组中删除元素: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如何修改此函数以设置我想从数组中删除的元素数量?谢谢!
查看完整描述

1 回答

?
函数式编程

TA贡献1807条经验 获得超9个赞

您的示例和问题不太清楚,但您可以查看此解决方案:


<?php


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'),


    "2"  => array (

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

    'params' => '',

    'price' => '12')

    );


    $prod_arr = array(

    "name"=> $prod_name,

    "params"=> $params,

    "price" => $price);


    $i = 0;


    while(($key = array_search($prod_arr, $cart)) !== false && $i < $count) {unset($cart[$key]); $i++;}


    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) }


查看完整回答
反对 回复 2021-12-03
  • 1 回答
  • 0 关注
  • 274 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信