如何从会话数组中删除行并重新排序数组列表


How to delete row from session array and again order array list?

我有一个网站,用户可以添加或删除自己喜欢的书。我在页面的每一行都添加了"添加"answers"删除"按钮。我可以在会话数组中添加最喜欢的书,这是没有问题的。但我不能从"用户最喜欢的书单"中删除一行

我使用了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;
 });

我认为问题出在del按钮id上。您使用的是$i变量而不是$items['id']。因此,JS重定向将向删除页面发送count 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>';