How to print an array with indexes and values in PHP?

4

I have the following array in PHP:

$matriz['HGF']['Christus'] = 7;
$matriz['HGF']['Unifor'] = 6;
$matriz['HIAS']['Christus'] = 5;
$matriz['HIAS']['Unifor'] = 4;

I would like to print the array in html, displaying indexes and values, like this:

<table>
   <tbody>
       <tr>
           <td> </td>
           <td> Christus </td>
           <td> Unifor </td>
       </tr>
       <tr>
           <td> HGF </td>
           <td align="center"> 7 </td>
           <td align="center"> 6 </td>
       </tr>
       <tr>
           <td> HIAS </td>
           <td align="center"> 5 </td>
           <td align="center"> 4 </td>
       </tr>
   </tbody>
</table>

I was able to do this in a one-dimensional array using foreach, but I'm not getting that array.

    
asked by anonymous 26.10.2017 / 16:31

2 answers

3
The first foreach will scroll through the array and grab the indices to create the top of the table and it has a break so that it runs only once, depending on how it is generated that array can be disorganized if all have the same indeces in the same order will be all ok, the second foreach will pick up the values and fill the table

The code would be as follows:

<?php 
    $matriz = array(
            "HGF" => array(
                    "Christus" =>7,
                    "Unifor" =>6,
            ),
            "HIAS"=>array(
                    "Christus" =>5,
                    "Unifor" =>4,
            )
    );
?>
<body>
    <table>
        <tbody>
            <tr>
                <td> </td>
                <?php 
                    foreach ($matriz as $key => $value) {
                        foreach ($value as $title => $result) {
                            $head .= "<td> " . $title . " </td>";
                        }
                        echo $head;
                        break;
                    }
                    foreach ($matriz as $key => $value) {
                        $body = "<tr>";
                        $body .= "<td> " . $key . " </td>";
                        foreach ($value as $title => $result) {
                            $head .= "<td> " . $title . " </td>";
                            $body .= "<td align='center'>" . $result . "</td>";
                        }
                        $body .= "</tr>";
                        echo $body;
                    }
                ?>
        </tbody>
    </table>
</body>
    
26.10.2017 / 17:09
3

It would be so, where you typed the values, you will print the array:

 <td><?php echo $matriz['HGF']['Cristus'] ?></td>
 <td><?php echo $matriz['HGF']['Unifor'] ?></td>

 <td><?php echo $matriz['HIAS']['Cristus'] ?></td>
 <td><?php echo $matriz['HIAS']['Unifor'] ?></td>

First, make sure you are passing the correct array to the page

    
26.10.2017 / 16:36