too*_*oop 2 html php arrays session
我正在向这样的二维数组添加内容:
$_SESSION['vehicles'][] = array ('model' => $_REQUEST['blah1'], 'price' => $_REQUEST['blah2'], 'year' => $_REQUEST['blah3']);
Run Code Online (Sandbox Code Playgroud)
我如何从会话中删除所有具有'model'=到我选择的变量的数组?(注意:会话中总会有许多具有相同模型的数组.)
我已经尝试过以下但它似乎没有从我的会话数组中删除任何东西:
$model = "toyota";
foreach ($_SESSION['vehicles'] as $vehicle)
{
unset($vehicle[$model]);
}
Run Code Online (Sandbox Code Playgroud)
谢谢!
小智 5
$ vehicle通过副本传递,因此,unset $ vehicle什么都不做
$model = "toyota";
foreach ($_SESSION['vehicles'] as $idx => $vehicle){
if($vehicle['model'] == $model){
unset($_SESSION['vehicles'][$idx]);
}
}
Run Code Online (Sandbox Code Playgroud)
$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; });
Run Code Online (Sandbox Code Playgroud)
或者,你的方法:
foreach ($_SESSION['vehicles'] as $key => $vehicle) {
if ($vehicle['model'] == $model) {
unset($_SESSION['vehicles'][$key]);
}
}
Run Code Online (Sandbox Code Playgroud)