Skip to content
Advertisement

Print a multidimensional array in a table, keys and values

I have the following array

$consulta2 = Array ( 
                    [AB] => Array ( [0] => Noah [1] => 48 ) 
                    [BC] => Array ( [0] => Jacob [1] => 42 ) 
                    [DA] => Array ( [0] => Mason [1] => 27 )
                   )

And I want to print in a table the array with KEYS and VALUES

Im currently using this foreach loop

foreach ($consulta2 as $key => $value){
        foreach ($value as $k => $v) {
          $template.= '<tr>
          <td class="service">'.$key.'</td>
          <td class="desc">'.$v.'</td> r n
          <td class="service">'.$v.'</td>
          <td class="service"></td>
          </tr>';
        }
    }

Im am getting the following table

+-----+-------+-------+
| Key | Value | Value |
+-----+-------+-------+
|  AB |  Noah |  Noah |
+-----+-------+-------+
|  AB |   48  |   48  |
+-----+-------+-------+
|  BC | Jacob | Jacob |
+-----+-------+-------+
|  BC |   42  |   42  |
+-----+-------+-------+
|  DA | Mason | Mason |
+-----+-------+-------+
|  DA |   27  |   27  |
+-----+-------+-------+

But I want it to look like this

+-----+-------+-------+
| Key | Value | Value |
+-----+-------+-------+
|  AB |  Noah |   48  |
+-----+-------+-------+
|  BC | Jacob |   42  |
+-----+-------+-------+
|  DA | Mason |   27  |
+-----+-------+-------+

If anyone knows how to fix it, I would be very grateful

Advertisement

Answer

Remove inner loop and access items of $value by keys (0 and 1):

foreach ($consulta2 as $key => $value){
    $template.= '<tr>
          <td class="service">'.$key.'</td>
          <td class="desc">'.$value[0].'</td> r n
          <td class="service">'.$value[1].'</td>
          <td class="service"></td>
          </tr>';
}
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement