Search code examples
phpmysqlcodeigniternested-loopshtml2pdf

How do I get the value of the sequential number of 2 pieces foreach function in codeigniter?


i have a problem with my code, because i use a nested foreach to get some value from my database. i need to get the value of the sequential number in my table.

I use this code :

    $TipeIklan          = $this->input->post('inputTipeIklan');
    $ProdukCode     = $this->input->post('inputPtodukCode');
    $Date               = $this->input->post('inputDate');
    $WherCustomer       = array("CustomerCode >="       => $Customer1,
                            "CustomerCode <="       => $Customer2);
    $ArrCustomer        = $this->customer_m->order_by("CustomerCode","ASC")->get_many_by($WherCustomer);

    if($ArrCustomer){
        foreach($ArrCustomer as $item_customer){
            $Kwitansi   = $this->kwitansi_m->getUmurPiutang($item_customer->CustomerCode,$ProdukCode,$Date);
            if($Kwitansi){
                $content .='
                            <tr>
                                <td class="fontB" colspan="17">'.$item_customer->CustomerCode.'</td>
                            </tr>';

                foreach($Kwitansi as $item){
                    $n  = count($Kwitansi);
                    $no = $n;
                    $content .='
                                <tr>
                                    <td class="font" width="200">'.$no.'</td>
                                </tr>';
                    $n++;           
                } ### end of foreach $Kwitansi as $item ###
            } ### end of $Kwitansi ###
        } ### end of foreach $ArrCustomer as $item_customer ###
    } ### end of $ArrCustomer ###

But I get a number like this, look at the left side of the document RESULT


Solution

  • Change your code

    foreach($Kwitansi as $item){
            $n  = count($Kwitansi);
            $no = $n;
            $content .='
                                <tr>
                                    <td class="font" width="200">'.$no.'</td>
                                </tr>';
            $n++;
    

    }

    to

    $m  = 0;
    foreach($Kwitansi as $item){
            $n = $m+1;
            $content .='
                                <tr>
                                    <td class="font" width="200">'.$no.'</td>
                                </tr>';
            $n++;
            $m++;
        }
    
     $n  = count($Kwitansi); this wrong because of if you got 5 count then start with 5,6,7...n. So, you need to put before loop and assign $n=1 to start with 1,2 .... so on