1

我有一个 php 文件,它从 txt 文件中读取信息并将其打印在屏幕上,例如

第一行 [ x ]
第二行 [ x ] 等等等等

我正在尝试在所有信息行旁边添加复选框,我设法做了一个 for 循环,根据读取的行数创建复选框。

现在我坚持的最后一件事是我希望用户能够单击任何复选框,然后单击提交按钮,该按钮应该在新的 php 文件上打印出所选信息。

如果用户勾选第一行并提交,那么它应该在打开的 php 文件上显示文本字符串“1st line”

我做了一些研究并设法使用 isset 方法来确定它是否被检查过,但我仍然不确定如何读取检查到新 php 文件中的信息任何帮助将不胜感激谢谢

$filename = "file.txt";

$filepointer = fopen($filename, "r"); //open for read

$myarray = file ($filename);

// get number of elements in array with count
for ($counts = 0; $counts < count($myarray); $counts++)

{ //one line at a time
$aline = $myarray[$counts];

//$par = array();
$par = getvalue($aline);

if ($par[1] <= 200) 
{ 

print "<input type=checkbox name='test'/>"." ".$par[0]." "; 
print $par[1]." ";
print $par[2]." ";
print $par[3]." ";

}

}
4

1 回答 1

2

I think you are probably wanting to create an array which identifies which lines were checked? Well, you'll want to use an array to name your checkbox inputs. You can do this with a very similar syntax to PHP, by appending [] to the input name. For this specific case, you'll also want to explicitly index the array keys, which you can do like [index]. It will be easier to demonstrate this in code:

file1.php (FIXED):

<?php

$filename = "file.txt";

// file() does not need a file pointer
//$filepointer = fopen($filename, "r"); //open for read

$myarray = file($filename);

print "<form action='file2.php' method='post'>\n";

// get number of elements in array with count
$count = 0; // Foreach with counter is probably best here
foreach ($myarray as $line) {

  $count++; // increment the counter

  $par = getvalue($line);

  if ($par[1] <= 200) {
    // Note the [] after the input name
    print "<input type='checkbox' name='test[$count]' /> ";
    print $par[0]." "; 
    print $par[1]." ";
    print $par[2]." ";
    print $par[3]."<br />\n";
  }

}

print "</form>";

file2.php:

<?php

  foreach ($_POST['test'] as $lineno) {
    print "Line $lineno was checked<br />\n";
  }

EDIT

Say you wanted file2.php to display the lines from the file that were checked:

<?php

  $filename = "file.txt";

  $myarray = file($filename);

  foreach ($_POST['test'] as $lineno) {
    // We need to subtract 1 because arrays are indexed from 0 in PHP
    print $myarray[$lineno - 1];
  }
于 2012-06-30T20:20:17.667 回答