如何从会话数组中删除行并重新排列数组列表?
我有一个网站,使用户能够添加或删除自己喜欢的书籍。我在页面的每一行添加了“添加”和“删除”按钮。我可以在会话数组中添加最喜欢的书,并且没有问题。但是我无法从“用户最喜爱的图书清单”中删除一行。如何从会话数组中删除行并重新排列数组列表?
我用jquery,ajax。我可以取消设置行,但我想要的是从会话中完全删除该行并重新排序。尽管我没有设置该行,但会话的元素号不会改变。
这里是代码:
//There are rows in $newdata. That is to say, newdata array is not empty now.
// I just add newdata array here to show that there is an array called newdata.
var $newdata = array();
function delete_row($rowid) {
if (isset($rowid)) {
$this->newdata = $this->session->userdata('contents');
unset($this->newdata[$rowid]['id']);
unset($this->newdata[$rowid]['name']);
unset($this->newdata[$rowid]['author']);
unset($this->newdata[$rowid]['year']);
$this->session->set_userdata(array('contents' => $this->newdata));
$contents = $this->session->userdata('contents');
$i = 0;
foreach ($contents as $key)
{
if ($key['id'] != "") {
$i++;
$this->newdata[$i]['id'] = $key['id'];
$this->newdata[$i]['name'] = $key['name'];
$this->newdata[$i]['author'] =$key['author'];
$this->newdata[$i]['year'] =$key['year'];
} else {
}
}
$this->session->set_userdata(array('contents' => $this->newdata));
} else {
echo "There is no row to be deleted";
}
}
这里是视图代码(HTML):
<div>
<?php
if (count($contents)==0) {
echo 'There is no favorite book';
} else {
echo '<table class="table table-striped">';
$i = 0;
echo count($contents);
foreach ($contents as $items) {
echo '<tr>';
echo '<td>'.$items['id'].'</td>';
echo '<td>'.$items['name'].'</td>';
echo '<td>'.$items['author'].'</td>';
echo '<td>'.$items['year'].'</td>';
echo '<td><button id='.$i .' class="delete_row"><b>DELETE</b></button></td>';
echo '</tr>';
$i++;
}
echo '</table>';
}
?>
</div>
这里是jQuery代码:
$('.delete_row').click(function(event) {
event.preventDefault();
var id = $(this).attr("id");
window.location.href = '/favorite/delete_row/'+id;
});
我认为问题出在德尔按钮ID。您正在使用$i
变量而不是$items['id']
。所以JS重定向将发送计数int而不是项目id
到删除页面。
变化:
echo '<td><button id='. $i .' class="delete_row"><b>DELETE</b></button></td>';
分为:
echo '<td><button id='. $items['id'] .' class="delete_row"><b>DELETE</b></button></td>';
这可能是问题所在。我会尝试... – kalaba2003 2012-08-04 12:23:04
亚,问题是关于id和$ items ['id']和其他一些问题。感谢您的回复。 – kalaba2003 2012-08-04 12:51:07
我不知道代码的具体运作,但我注意到:如果(isset($ ROWID)){ - >是总是如此,因为$ rowid被函数传递。尝试将其设置为会话变量。应该有所帮助。 – ATaylor 2012-08-04 12:15:21