douchunsui2395 2011-10-31 13:16
浏览 20
已采纳

如何在一个表中统一3个文件?

I have a test script, that generate txt file with answers. And have 2 txt files with the correct answers. I want: 1) Unite all files in one table, like:

<table>
<tr>
<td>№ of question</td>
<td>data from file 1</td>
<td>data from file 2</td>
<td>data from file 3</td>
</tr>
...
</table>

2) I want to replace id in this files on text from DB (MySQL). I have table with question and answers with similar id (like in txt files).

All files have structure like:

1|3
2|4
3|1

where first number - is id of a question, and second is a variant of answer.

I start coding, but don't know how to include data from files:

// Slect from DB
$qsel=mysql_query("SELECT `qid`, `qtext` from `questions` ORDER BY `qid`");

// Open file 1 
$key1=fopen("data/test_1_key1.txt", "r");
$k1=explode("/r/n", $key1);

// Open file 2 
$key2=fopen("data/test_1_key2.txt", "r");
$k2=explode("/r/n", $key2);

$rtable='<table border="1" cellspacing="0" cellpadding="3">
    <tr>
      <th width="40%">Q</th>
      <th width="20%">A 1</th>
      <th width="20%">A 2</th>
      <th width="20%">NAME</th>
    </tr>';
  while($q=mysql_fetch_row($qsel))
  {

    $rtable.='<tr><td><b>'.$q['1'].'</b></td>'; 
    $rtable.='<td>data from file 1</td>'; 
    $rtable.='<td>data from file 2</td>'; 
    $rtable.='<td></td>'; 
  }
  echo '</table>'.$rtable;
  • 写回答

1条回答 默认 最新

  • duanjianshen4871 2011-11-01 23:23
    关注

    I would first fetch the textfiles and convert it into indexed array:

    $tmp1 = file('text1.txt');
    $data1 = array();
    foeach($tmp1 as $line)
    {
        list($key1, $val1) = explode("|", $line);
        $data1[$key1] = $val1;
    }
    

    and then, on mysql fetch loop, just use the indexed array:

    while($q=mysql_fetch_row($qsel))
    {
    
        $rtable.='<tr><td><b>'.$q['1'].'</b></td>'; 
        $rtable.='<td>' . ( isset( $data1[ $q['0'] ] ) ? $data1[ $q['0'] ] : '' ) . '</td>'; 
        $rtable.='<td>data from file 2</td>'; 
        $rtable.='<td></td>'; 
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程