简体   繁体   中英

php unset array from 2d session array

i am adding stuff to a 2d array like this:

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

how would i remove all arrays from the session that have a 'model' = to a variable of my choice? (note: there will always be many arrays in the session with the same model.)

i have tried the below but it doesn't seem to remove anything from my session array:

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

Thanks!

$vehicle is passed by copy, so, unset $vehicle do nothing

$model = "toyota";
foreach ($_SESSION['vehicles'] as $idx => $vehicle){
    if($vehicle['model'] == $model){
        unset($_SESSION['vehicles'][$idx]);
    }
}
$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; });

Or, your approach:

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

You have to :

  • iterate over your vehicles
  • for each vehicle, test if its model is the one you are looking for
  • and if yes, delete it :


Which could be translated by a portion of code like this one :

$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]);
    }
}
foreach($_SESSION['vehicles'] as $key => $vehicle) {
    if($vehicle['model'] == "toyota") {
        unset($_SESSION['vehicles'][$key]);
    }
}

Should do it.

I need to write my answers faster.

what you are trying to remove is $vehicle['toyota'] which is not present in the arrays

try this instead ..

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

At first note that $_SESSION['vehicles'] is a numbered array, so $vehicle[$model] just can't work. Next to modify item in the foreach loop:

As of PHP 5, you can easily modify array's elements by preceding $value with &. This will assign reference instead of copying the value.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM