【问题标题】:The count should reset when the name changes名称更改时应重置计数
【发布时间】:2022-01-05 10:46:40
【问题描述】:

我的目标是在名称更改时应重置计数。正如我们在表 1 中看到的,即使名称发生了变化,计数仍在继续。

我目前的输出:

id name count
1 juan 1
2 juan 2
3 juan 3
4 dela 4
5 dela 5
6 dela 6
7 cruz 7
8 cruz 8
9 cruz 9
10 cruz 10
11 cruz 11

我的目标输出:

id name count
1 juan 1
2 juan 2
3 juan 3
4 dela 1
5 dela 2
6 dela 3
7 cruz 1
8 cruz 2
9 cruz 3
10 cruz 4
11 cruz 5

正如我们在表 2 中看到的,由于名称更改,计数会重置。

控制器:

public function lists()
    {
        
        
        $list = $this->lists->get_datatables();
        $json = array();
        $no = $_POST['start'];
        $count = '1';
        foreach ($list as $list) {
            
       
            $no++;
           $row = array();
            $row[] = '<tr><td>'.$list->id.'</td>';
            $row[] = '<tr><td>'.$list->Name.'</td>';
            $row[]='<td>'. $count++.'</td>';
 
            
            $data[] = $row;
            
        }
        
        $output = array(
            "draw" => $_POST['draw'],
            "recordsTotal" => $this->lists->count_all(),
            "recordsFiltered" => $this->lists->count_filtered(),
            "data" => $data,
        );
        //output to json format
        echo json_encode($output);
    }

【问题讨论】:

    标签: codeigniter codeigniter-3


    【解决方案1】:

    这应该可以工作

    public function lists()
    {
        
        
        $list = $this->lists->get_datatables();
        $json = array();
        $no = $_POST['start'];
        $count = '1';
    
        $check_arr = array();
    
        foreach ($list as $list) {
           
    
           if(!empty($check_arr) && !in_array($list->Name, $check_arr))  {         
             $count = 1;
           }
    
           $no++;
           $row = array();
           $row[] = '<tr><td>'.$list->id.'</td>';
           $row[] = '<tr><td>'.$list->Name.'</td>';
           $row[]='<td>'. $count++.'</td>';
    
           $check_arr[] = $list->Name;
            
        }
        
        $output = array(
            "draw" => $_POST['draw'],
            "recordsTotal" => $this->lists->count_all(),
            "recordsFiltered" => $this->lists->count_filtered(),
            "data" => $data,
        );
        //output to json format
        echo json_encode($output);
    }
    

    【讨论】:

    • 非常感谢。真是个救星。
    • 我可以请您解释一下您的答案吗?由于我正在学习...您的解释将有助于我了解更多。
    • @UlquiorraSchiffer 当数组中没有新元素时,他会重置$count = 1。通过以下方式检查:!in_array($list-&gt;Name, $check_arr)$count = 1当数组的第一个元素也是:!empty($check_arr)
    猜你喜欢
    • 2017-01-14
    • 1970-01-01
    • 2011-02-21
    • 2021-07-11
    • 1970-01-01
    • 2020-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多