【问题标题】:Get PHP array values and print in a loop [duplicate]获取PHP数组值并循环打印[重复]
【发布时间】:2014-08-05 19:46:58
【问题描述】:

我有一个有 9 行的表。第一列应打印排名的每个参与者的姓名。首先,我做了一个包含它们名称的数组:

$names = array("Mike", "Kyle", "Johnny", "Will", "Vasques");

对于这个任务,我编写了一个 5 行 10 列的循环。因此,正如我所提到的,第一列应该打印每个人的名称。

for($x=1; $x<=count($names); $x++) {
  echo "<tr>";
  for($td=1; $td<=10; $td++) {
    echo "<td></td>";
  }
  echo "</tr>";
}

如您所见,&lt;tr&gt; 有一个循环,&lt;td&gt; 内部有一个循环!如何打印第一行中的每个名称?

【问题讨论】:

标签: php arrays loops html-table


【解决方案1】:

先打印名称,然后再打印 9 个td。 (必须将 $x 从 0 更改为 count($names)-1 以匹配 $names 的索引)

for($x=0; $x<count($names); $x++) {
  echo "<tr>";
  echo "<td>$names[$x]</td>";
  for($td=2; $td<=10; $td++) {
    echo "<td></td>";
  }
  echo "</tr>";
}

【讨论】:

  • 效果更好!干杯! =D
【解决方案2】:

对空单元格使用foreach 循环和array_fill

// Set the names array.
$names = array("Mike", "Kyle", "Johnny", "Will", "Vasques");

// Set the table cell start key.
$table_cell_start_key = 0;

// Set the table cell count.
$table_cell_count = 9;

// Set the table cells.
$table_cells = implode("", array_fill($table_cell_start_key, $table_cell_count, '<td></td>'));

// Loop through the names array & echo output.
foreach($names as $name) {
  echo "<tr>"
     . "<td>$name</td>"
     . $table_cells
     . "</tr>"
     ;
}

使用array_fill 的好处是您可以在foreach 循环之前简单地设置$table_cells 的值。然后foreach 循环只是基于$names 渲染内容,额外的表格单元格被放入。

【讨论】:

    【解决方案3】:
    $names = array("Mike", "Kyle", "Johnny", "Will", "Vasques");
    for($td=0; $td<=9; $td++) {
      echo "<tr>";
      if ($td == 0) {
        foreach ($names as $name) {
          echo "<td>$name</td>";
        }
      }
      echo "<td></td>";
      echo "</tr>";
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-12
      • 2016-01-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多