0

I need to also append the table header dynamic as per the json array value using PHP. I am explaining my code below.

<?php
$resultArr=array(array("header"=>"Firstname","data"=>array("Jack","Ram")),array("header"=>"Lastname","data"=>array("Nayak","Das")),array("header"=>"Age","data"=>array("50","30")));
?>
<!doctype html>
<html>
<head>
<title>Demo Preview</title>
<meta name="robots" content="noindex, nofollow"/>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>
<style>
table, th, td {
    border: 1px solid black;
    border-collapse: collapse;
}
</style> 
</head>
<body>
<table style="width:100%">
  <tr>
    <th>Firstname</th>
    <th>Lastname</th> 
    <th>Age</th>
  </tr>
  <tr>
    <td>Jack</td>
    <td>Nayak</td>
    <td>50</td>
  </tr>
  <tr>
    <td>Ram</td>
    <td>Das</td>
    <td>30</td>
  </tr>
</table>
</body>
</html>

Here I have the static values inside the table. I need to add the same values dynamically as per the array(i.e-$resultArr) using PHP.

1
  • 2
    foreach() is your friend. There are dozens of tutorials on it. Commented Nov 1, 2018 at 8:00

1 Answer 1

1
<?php
$resultArr=array(array("header"=>"Firstname","data"=>array("Jack","Ram")),array("header"=>"Lastname","data"=>array("Nayak","Das")),array("header"=>"Age","data"=>array("50","30")));

$nbPerson = count($resultArr[0]['data']);

?>
<!doctype html>
<html>
<head>
<title>Demo Preview</title>
<meta name="robots" content="noindex, nofollow"/>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>
<style>
table, th, td {
    border: 1px solid black;
    border-collapse: collapse;
}
</style> 
</head>
<body>
<table style="width:100%">
  <tr>
    <?php
        foreach($resultArr as $key => $array)
        {
            echo '<th>'.$array['header'].'</th>';
        }
    ?>
  </tr>
    <?php
        $i = 0;
        while($i < $nbPerson)
        {
            echo '<tr>';
            foreach($resultArr as $key => $array)
            {
                echo '<td>'.$array['data'][$i].'</td>';
            }
            echo '</tr>';
            $i++;
        }
    ?>
</table>
</body>
</html>

To test it: https://3v4l.org/NrQcI

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

Comments

Your Answer

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