从2d会话数组的php unset数组

时间:2011-04-25 12:10:44

标签: php html arrays session

我正在向这样的二维数组添加内容:

 $_SESSION['vehicles'][] = array ('model' => $_REQUEST['blah1'], 'price' => $_REQUEST['blah2'], 'year' => $_REQUEST['blah3']);  

如何从会话中删除所有具有'model'=到我选择的变量的数组? (注意:在具有相同模型的会话中将始终存在许多数组。)

我已经尝试了以下但它似乎没有从我的会话数组中删除任何东西:

$model = "toyota";
foreach ($_SESSION['vehicles'] as $vehicle) 
{
    unset($vehicle[$model]);
}

谢谢!

6 个答案:

答案 0 :(得分:5)

$ vehicle通过副本传递,因此,unset $ vehicle什么都不做

$model = "toyota";
foreach ($_SESSION['vehicles'] as $idx => $vehicle){
    if($vehicle['model'] == $model){
        unset($_SESSION['vehicles'][$idx]);
    }
}

答案 1 :(得分:5)

$model = 'toyota';

// PHP <= 5.2
$_SESSION['vehicles'] = array_filter($_SESSION['vehicles'],
              create_function('$v', "return \$v['model'] != '$model';"));

// PHP 5.3+
$_SESSION['vehicles'] = array_filter($_SESSION['vehicles'],
              function ($v) use ($model) { return $v['model'] != $model; });

或者,你的方法:

foreach ($_SESSION['vehicles'] as $key => $vehicle) {
    if ($vehicle['model'] == $model) {
        unset($_SESSION['vehicles'][$key]);
    }
}

答案 2 :(得分:4)

你必须:

  • 遍布你的车辆
  • 对于每辆车,测试其型号是否是您正在寻找的型号
  • 如果是,请删除它:


这可以通过像这样的代码的一部分来翻译:

$model = "toyota";
foreach ($_SESSION['vehicles'] as $key => $vehicle) 
{
    if ($vehicle['model'] == $model) {
        // The current vehicle's model is what you are searching for
        // => delete if from $_SESSION
        unset($_SESSION['vehicles'][$key]);
    }
}

答案 3 :(得分:3)

foreach($_SESSION['vehicles'] as $key => $vehicle) {
    if($vehicle['model'] == "toyota") {
        unset($_SESSION['vehicles'][$key]);
    }
}

应该这样做。

我需要更快地写下答案。

答案 4 :(得分:2)

您要删除的内容是$vehicle['toyota'],这在数组中不存在

试试这个......

$model = "toyota";
foreach ($_SESSION['vehicles'] as $key=>$vehicle) 
{
    if($model == $vehicle['model']) {
         unset($_SESSION['vehicles'][$key]);
    }    
}

答案 5 :(得分:0)

首先请注意$ _SESSION ['vehicles']是一个带编号的数组,因此$ vehicle [$ model]无法正常工作。接下来修改foreach循环中的项目:

  

从PHP 5开始,您可以轻松修改   数组前面的$ value元素   与&amp ;.这将指定参考   而不是复制价值。

$model = "toyota";
foreach ($_SESSION['vehicles'] as &$vehicle) 
{
    if ($vehicle['model'] == $model)
         unset($vehicle);
}