Search code examples
codeignitercodeigniter-3

The count should reset when the name changes


My target is the count should reset when the name has changed. As we can see in table 1, the count continues even the name changed.

My current output:

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

My target output:

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

As we can see here in table 2, the count reset because the name changes.

Controller:

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);
    }

Solution

  • This should work

    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);
    }