是否可以/如果该元素是数组并且它具有特定元素,我将如何删除数组元素?我有一个来自会话的数组(我正在使用laravel 4)。
我使用它将它添加到会话
Session::push('answers', array('exam_id' => $exam, 'question_id' => $index, 'answer_id' => $answer));
并获得答案以及如何删除它们
$values = Session::get('answers');
foreach ($values as $index1 => $value) {
if ($value['exam_id'] == $examid && $value['question_id'] == $questionid) {
// Delete Array from session
}
}
例如,如果$value['exam_id'] = 1
和$value['question_id'] = 2
从此
"answers":[{"exam_id":"1","question_id":"1","answer_id":"3"},{"exam_id":"1","question_id":"2","answer_id":"6"}]
我想得到
"answers":[{"exam_id":"1","question_id":"1","answer_id":"3"}]
答案 0 :(得分:2)
如果要从多维数组中删除特定数组,可以使用unset
方法,指定要删除的子数组的索引。
$values = Session::get('answers');
foreach ($values as $index => $value) {
if ($value['exam_id'] == $examid && $value['question_id'] == $questionid) {
unset($values[$index]);
break;
}
}
结果将是:
Array
(
[0] => Array
(
[exam_id] => 1
[question_id] => 1
[answer_id] => 3
)
)
答案 1 :(得分:0)
如果您需要删除整个数组,请调用forget。
Session::forget('answers');
如果你需要删除数组的特定元素,我认为你可以组合get和set操作。
$values = Session::get('answers');
//...do something to $values, then
Session:put('answers', $values);