Javascript/PHP,使用文本文件作为数据库,并将内容组织到阵列表中


Javascript/PHP, use text file as a database and organize content into an arrayed table

我正在努力找到最简单的方法。(PHP或Javascript)基本上,我有一个文本文件,看起来像这样:

1
的
de/dí /dì 
(possessive particle)/of, really and truly, aim/clear
2
一
yī 
one/1/single/a(n)
3
是
shì 
is/are/am/yes/to be
4
不
bù /bú 
(negative prefix)/not/no
5
了
le/liǎo /liào 
(modal particle intensifying preceding clause)/(completed action marker), to know/to understand/to know, clear, look afar from a high place

我想读取数据并将其插入到一个表中,例如:

<table cellpadding="0" cellspacing="0" border="1">
    <tr>
      <td width="50" height="50" align="center">1</td>
      <td width="50" height="50" align="center" >的</td>
      <td width="50" height="50" align="center">de/dí /dì</td>
        <td width="50" height="50" align="center">(possessive particle)/of, really and truly, aim/clear</td>
    </tr>
        <tr>
      <td width="50" height="50" align="center">2</td>
      <td width="50" height="50" align="center">一</td>
      <td width="50" height="50" align="center">yī </td>
        <td width="50" height="50" align="center">one/1/single/a(n)</td>
    </tr>
</table>

我想有两种方法可以做到这一点。第一种是将内容组织成变量(1a、1b、1c、1d、2a、2b、2c、2d…),然后找到一些方法,以最小的努力将变量插入一组表中。

第二种方法是将数据组织成一个数组,然后将数据数组生成一个表。我认为这可能是最好的方法,但我需要能够指定表的哪一部分(如第1页(条目1-100)等)。

如果文件中的每个数据集总是由4行组成,则可以通过以下方式生成表行:

<?php
$rows=file('path/to/file.txt');
$start=1;
$max=100;
echo '<tr>';
for($length=count($rows); $start<=$length && $start<=$max; $start++){
    echo '<td>',$rows[$start-1],'</td>';
    if($start %4 == 0) echo '</tr><tr>';
}
echo '</tr>';
?>

然后你只需要围绕它构建表的其余部分。在CSS文件中设置格式(比如高度)。要只显示部分数据,只需相应地设置$start$max变量即可。为了简洁起见,我把它写得很短。显然,添加检查,比如文件是否真的是空的等等…

假设每个条目总是有4行,首先将文件读取到一个数组中,其中每个值都是一行。然后创建一个每4行迭代一次的循环(i=i+4),在循环的主体中,访问相对于当前迭代的每个元素(line[i],line[i+1],line[i+2],line[i+3])。

或者,您可以使用JSON数组将数据存储在一个文件中,其中每个值都是它自己的对象,其中每个条目都作为它自己的键。PHP和JavaScript都支持读取和写入JSON。然后,您可以循环遍历生成的数组并指向所需的键。