Export array within a table?

Asked

Viewed 544 times

4

I need to export data from an array inside an html table, the function is working but I don’t know how to export while inside a table, I made an analogy with the code below.

function imprimir_Tbl($Id, $Nome){
$array = array();

for($i=0; $i<= $Id; $i++){
    $array["id"][] = $i + 1;
    $array["nome"][] = $Nome.' '.($i + 1);
}
return $array;}

Using var_dump the data is printed correctly, the expected result is as follows

<table border="0">
<thead>
    <tr>
        <th>Id</th>
        <th>Nome</th>
    </tr>
</thead>
<tbody>
    <tr>
        <td>1</td>
        <td>Nome 1</td>
    </tr>
    <tr>
        <td>2</td>
        <td>Nome 2</td>
    </tr>
    <tr>
        <td>3</td>
        <td>Nome 3</td>
    </tr>
    <tr>
        <td>4</td>
        <td>Nome 4</td>
    </tr>
</tbody>

inserir a descrição da imagem aqui

  • Do you want to use that function to fill the table? Or is the function just to fill the array?

  • @Localhost I have a function that makes several calculations and at the end it returns an array with the result and the result I need to be presented in a table where $array["id"][0] coincides with the second column $array["name"][0], I hope to have solved the doubt, and thank you.

  • 1

    Oh yes, I understand. Because the way you put it makes it seem like your array was useless, because it’s just a way for you to print the table

1 answer

3


You can use the foreach to list the results in HTML.

In the PHP function you can join the ID with the Name in the same Array, by using the variable $i of for.

PHP

<?php

function imprimir_Tbl($Id, $Nome){
    $array = array();

    for($i = 0; $i <= $Id; $i++){
        $array[$i]["id"]    = $i + 1;
        $array[$i]["nome"]  = $Nome.' '.($i + 1);
    }
    return $array;

}

$array = imprimir_Tbl(10, 'Nome');

HTML

<table border="0">
<thead>
    <tr>
        <th>Id</th>
        <th>Nome</th>
    </tr>
</thead>
<tbody>

<?php
   foreach($array as $key => $value){
?> 

<tr>
   <td><?=$value['id']?></td>
   <td><?=$value['nome']?></td>
</tr>

<?php   
   }
?>

</tbody>
  • 1

    thanks a lot for the force, the foreach solved the problem, I made a change to insert the data in Bd.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.