1

I have data in a php array that gives the below output. I am trying to format this data into an HTML table:

$persen = array(                                             
    array(73671348, 2),                                      
    array(23387730, 4),                                      
    array(21258277, 1),                                      
    array(0, 0),                                         
    array(0, 0),                                         
    array(0, 0)
);

I tried to use the below code to populate the table:

for ($i = 0; $i < count($persen); $i++)
{                                            
    for ($j = 0; $j < $persen[$i][1]; $j++)                                          
    {                                            
    $noID1 = $i+$j+1;                                        
    $um1 = $persen[$i][0];                                          

    echo '<tr><td>'.$noID1.'</td>                                                
    <td class="text-right">'.$um1.'</td></tr>';                                          
    }
}

I get the below output:

NO  VALUE
------------
1   73671348
2   73671348
2   23387730
3   23387730
4   23387730
5   23387730
3   21258277

I want the final results to be like the following

NO  VALUE
------------
1   73671348
2   73671348
3   23387730
4   23387730
5   23387730
6   23387730
7   21258277

Could someone please help?

2 Answers 2

2
$counter = 0;
for ($i = 0; $i < count($persen); $i++)
{
    for ($j = 0; $j < $persen[$i][1]; $j++)
    {
        $counter = $counter +1;
        $noID1 = $i+$j+1;
        $um1 = $persen[$i][0];

        echo '<tr><td>'.$counter.'</td>                                                
    <td class="text-right">'.$um1.'</td></tr>';
        echo '<br>';
    }
}

The output of the above code:

1 73671348
2 73671348
3 23387730
4 23387730
5 23387730
6 23387730
7 21258277

You kinda mixed the counters there. You simple needed a counter that increases once per loop.

Sign up to request clarification or add additional context in comments.

Comments

1

You could do it like this:

foreach ($persen as $row) {
    echo str_repeat("<tr><td></td><td>$row[0]</td></tr>", $row[1]);
}

And then autonumber the rows with CSS.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.