Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/codeigniter/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 如何在数据库中按优先级存储数据?_Php_Codeigniter - Fatal编程技术网

Php 如何在数据库中按优先级存储数据?

Php 如何在数据库中按优先级存储数据?,php,codeigniter,Php,Codeigniter,我想将我的分类列表以优先级存储在数据库中…如 cat_id cat_name cat_priority --------------------------------- 1 Test1 1 2 Test2 2 3 Test3 3 4 Test4 4 现在如果我必须将Test1priority设置为3,以及我需要在表结构中更改的内容。每次您要更改项目优先级时,

我想将我的分类列表以优先级存储在数据库中…如

cat_id   cat_name   cat_priority
---------------------------------
 1        Test1         1
 2        Test2         2
 3        Test3         3
 4        Test4         4

现在如果我必须将
Test1
priority设置为3,以及我需要在表结构中更改的内容。

每次您要更改项目优先级时,都必须为每个项目重新分配优先级。我想您不想重复优先级

//$category = ...

//get all categories
$categories = $this->db->order_by('cat_priority')->select('cat_id, cat_priority')->get();

$cat_to_change = $category['cat_id'];
$new_priority = 2;
$i_priority = 0;
$new_categories = array();

foreach($categories->result_array() as $row)
{
    //this is the category we want to change, so change it
    if($row['cat_id'] == $cat_to_change)
    {
        $row['cat_priority'] = $new_priority;
    }
    else
    {
        //increment the priority
        $i_priority++;

        //the new priority is owned by another cat
        //so let it for the cat we want for him
        if($row['cat_priority'] == $new_priority)
            $i_priority++;

        $row['cat_priority'] = $i_priority;
    }

    $new_categories[] = $row;
}

//save
$this->db->update_batch('categories', $new_categories, 'cat_id'); 

没有测试它。希望有帮助。

最简单的方法是使用新的cat\U优先级更新所有行。确保你没有修改cat_id。哦..你的意思是说如果我有很多数据…那么我们需要执行大量查询。。。。。。。。。。。。!!!!!!!对你的UI看起来怎么样?所有类别都正确吗?如果您想限制您的查询,并且您的UI是拖放式的或类似的,您可以在cat_优先级上进行交换。