douluoqiu4538 2013-05-26 15:24 采纳率: 100%
浏览 23
已采纳

从数组中删除[重复]

This question already has an answer here:

i have an array that looks like this:

Array ( 
    [0] => Array ( 
        [id] => 18 
        [name] => book 
        [description] => 
        [quantity] => 0 
        [price] => 50 
        [status] => Brand New
    ) 
    [1] => Array ( 
        [id] => 19 
        [name] => testing   
        [description] => for testing 
        [quantity] => 2 
        [price] => 182 
        [status] => Brand New
    ) 
    [2] => Array ( 
        [id] => 1 
        [name] => Fruity Loops 
        [description] => dj mixer 
        [quantity] => 1     
        [price]  => 200 
        [status] => Brand New
    ) 
)

I want to be able to delete an entire row in the array (when a user clicks a delete link) say array[1] which is:

[1] => Array ( 
    [id] => 19 
    [name] => testing   
    [description] => for testing 
    [quantity] => 2 
    [price] => 182 
    [status] => Brand New
)

I have this code where i'm trying to delete based on the id of the product but it doesn't work

//$_SESSION['items'] is the array and $delid is the "product id" gotten when a user clicks  delete on a particular row.
foreach ($_SESSION['Items'] as $key => $products) { 
    if ($products['id'] == $delid) {
        unset($_SESSION['Items'][$key]);
    }
}

How do i implement this? Thanks

</div>
  • 写回答

2条回答 默认 最新

  • douluohan3403 2013-05-26 15:28
    关注

    You could pass $_session into an ArrayIterator and use ArrayIterator::offsetUnset().

    For example:-

    session_start();
    
    $_SESSION['test1'] = 'Test1';
    $_SESSION['test2'] = 'Test2';
    $_SESSION['test3'] = 'Test3';
    
    var_dump($_SESSION);
    $iterator = new ArrayIterator($_SESSION);
    $iterator->offsetUnset('test2');
    $_SESSION =  $iterator->getArrayCopy();
    
    var_dump($_SESSION);
    

    Output:-

    array (size=3)
      'test1' => string 'Test1' (length=5)
      'test2' => string 'Test2' (length=5)
      'test3' => string 'Test3' (length=5)
    
    array (size=2)
      'test1' => string 'Test1' (length=5)
      'test3' => string 'Test3' (length=5)
    

    This also saves you the expense of looping through the array to find the element you want to delete.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛