Get PHP array values and print it on different columns

泪湿孤枕 提交于 2019-11-29 17:57:00

Try this

echo "<table>";
foreach($scores as $key=>$value)
{
     echo "<tr>";
     echo "<td>$key</td>";
     for($x=0; $x<count($value); $x++) 
     {
         echo "<td>".sprintf('%02d', $value[$x])."</td>";
     }
     echo "</tr>";
}
echo "</table>";

Example full code view

    <?php
//Names
$names = array("Mike", "Kyle", "Johnny", "Will", "Vasques");

//scores values for each name
$scores = array(
    "Mike"    => array(04, 03, 00, '-', '-', '-', '-', '-', '-', 07, 04),
    "Kyle"    => array(07, 01, 00, 03, 04, 01, 00, 07, 03, 04, 04),
    "Johnny"  => array(07, 07, 00, 03, 00, 04, 00, 01, 01, 04, 03),
    "Will"    => array(03, 04, 00, 03, 04, 07, 00, 01, 00, 07, 04),
    "Vasques" => array(03, 01, 00, 03, 04, 07, 00, 01, 00, 07, 07)
);
echo "<table>";
foreach($scores as $key=>$value)
{
     echo "<tr>";
     echo "<td>$key</td>";
     for($x=0; $x<count($value); $x++) 
     {
          if (is_numeric($value[$x])) 
     {
        echo "<td>".sprintf('%02d', $value[$x])."</td>";
     }
     else
     {
         echo "<td>". $value[$x]."</td>";
     }
     }
     echo "</tr>";
}
echo "</table>";

Output

Mike    04  03  00  -   -   -   -   -   -   07  04
Kyle    07  01  00  03  04  01  00  07  03  04  04
Johnny  07  07  00  03  00  04  00  01  01  04  03
Will    03  04  00  03  04  07  00  01  00  07  04
Vasques 03  01  00  03  04  07  00  01  00  07  07

You don't need the $names array, you can just output it as the first level array key. Here's an example using foreach() instead of numeric for() loops for cleaner code:

foreach($scores as $name => $values) {
    echo '<tr><td>' . $name . '</td>' . PHP_EOL;
    foreach($values as $val) {
      echo '<td>' . $val . '</td>' . PHP_EOL;
    }
    echo '</tr>' . PHP_EOL;
}
<?php
foreach($names as $names)
{
   echo "<tr>";
   echo "<td>$names</td>";
   foreach($scores[$names] as $nmscore)
   {
        echo "<td>$nmscore</td>";

   }
echo "</tr>";
}

?>

<?php
foreach($names as $name)
{
   echo "<tr>";
   echo "<td>$name</td>";
   foreach($scores[$name] as $nmscore)
   {
        echo "<td>$nmscore</td>";

   }
echo "</tr>";
}

?>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!