简体   繁体   中英

Multidimensi array into html table with PHP

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?

$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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM