如何从会话数组中删除行并再次排序数组列表?

时间:2012-08-04 12:10:12

标签: php codeigniter session

我有一个网站,可以让用户添加或删除自己喜欢的书籍。我在页面的每一行添加了“添加”和“删除”按钮。我可以在会话数组中添加喜爱的书籍,没有任何问题。但我无法从“用户最喜欢的图书清单”中删除一行。

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

 });

1 个答案:

答案 0 :(得分:1)

我认为问题在于del按钮id。您使用的是$i变量而不是$items['id']。所以JS重定向会将count int而不是item 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>';