Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
74 views
in Technique[技术] by (71.8m points)

php - 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.

question from:https://stackoverflow.com/questions/65869680/html-table-printing-from-array

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...