Skip to content
Advertisement

Html table printing from array

I have a csv in such a format. I am trying to build an html table like show below.

  Sem 1 , Subj 1 , 75 , 100 ;
  Sem 1 , Subj 2 , 95 , 100 ;
  Sem 1 , Subj 3 , 88 , 100 ;
  Sem 2 , Subj 2 , 95 , 100 ;
  Sem 2 , Subj 3 , 85 , 100 ;
  Sem 3 , Subj 4 , 87 , 100 ;
  Sem 4 , Subj 1 , 84 , 100 ;
   

HTML Table

      Sem 1  Sem 2  Sem 3  Sem 4
Subj 1   75      X     X     84
Subj 2   95     95     X     X 
Subj 3   88     85     X     X 
Subj 4   X      X      87    X 

// This is what i have came up with . Which is currently printing only the heading

$datas = [
["Sem 1" , "Subj 1" , "75" , "100"],
["Sem 1" , "Subj 2" , "95" , "100"],
["Sem 1" , "Subj 3" , "88" , "100"],
["Sem 2" , "Subj 2" , "95" , "100"],
["Sem 2" , "Subj 3" , "85" , "100"],
["Sem 3" , "Subj 4" , "87" , "100"],
["Sem 4" , "Subj 1" , "84" , "100"]];


  
$unique_coloum = [];
echo "<tr>";
foreach($datas as $data){
    if(!in_array($data[0],$unique_coloum)){
        echo "<td>".$data[0]."</td>";
        array_push($unique_coloum,$data[0]);
    }       
}
echo "</tr>";   
foreach($datas as $data){
   #?
}
    

The Sem and Subj are n. I am stuck at for loop logic on how about to start. Any help would be great.

Advertisement

Answer

You can use next solution:

<?php
$datas = [
    ["Sem 1" , "Subj 1" , "75" , "100"],
    ["Sem 1" , "Subj 2" , "95" , "100"],
    ["Sem 1" , "Subj 3" , "88" , "100"],
    ["Sem 2" , "Subj 2" , "95" , "100"],
    ["Sem 2" , "Subj 3" , "85" , "100"],
    ["Sem 3" , "Subj 4" , "87" , "100"],
    ["Sem 4" , "Subj 1" , "84" , "100"]
];

$columns = array_column($datas, 0, 0);

sort($columns);
// var_export($columns);

$res = array_reduce(
    $datas,
    function($res, $data) {
        if (!isset($res[$data[1]])) $res[$data[1]] = [];
        $res[$data[1]][$data[0]] = $data[2];
        return $res;
    },
    $res
);

// var_export($res);

$output = "<tr><th>subject</th>" . implode('</th><th>', $columns) . '</th></tr>' . PHP_EOL;

foreach($res as $key => $row) {
    $output .= "<tr><td>$key</td>";
    foreach($columns as $col) {
        $output .= $row[$col] ? "<td>$row[$col]</td>" : "<td>X</td>";
    }
    $output .= "</tr>" . PHP_EOL;
}

echo $output;

share PHP code

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement