PHP:为什么浏览器输出显示在页面顶部?

时间:2017-01-12 19:24:25

标签: php html css foreach

我从html文件中的表单中获取数字,目前的目标是简单地输出数字范围。但是,它们出现在我的h1标题之上,位于屏幕顶部和h1标记之下。我之前遇到过这种情况,但不能为我的生活记住问题所在。

<?php
$input = $_GET["number"];
$range = range(0, $input);
$output = pingpong($range);

function pingpong($fx_range)
{
  foreach ($fx_range as $number) {
    echo $number . ", ";
  }
}
?>


<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Ping Pong</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css">
  </head>
  <body>
    <div class="container">
      <h1>Ping Pong Results</h1>
      <?= $output . " "; ?>
    </div>
  </body>
</html>

输出如下:

0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,

       Ping Pong Results

提前致谢。

2 个答案:

答案 0 :(得分:2)

你可以这样做:

<?php
$input = $_GET["number"];
$range = range(0, $input);
//$output = pingpong($range);

function pingpong($fx_range)
{
  foreach ($fx_range as $number) {
    echo $number . ", ";
  }
}
?>


<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Ping Pong</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css">
  </head>
  <body>
    <div class="container">
      <h1>Ping Pong Results</h1>
      <?php pingpong($range); ?>
  </body>
</html>

修改

只是为了向您展示一种方法,您可以从函数返回一个数组,并通过foreach输出HTML中的值:

<?php
$input =$_GET["number"];
$range = range(0, $input);
$output = pingpong($range);

function pingpong($fx_range)
{
  foreach ($fx_range as $number) {
    $result[] = $number;
  }
  return $result;
}
?>


<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Ping Pong</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css">
  </head>
  <body>
    <div class="container">
      <h1>Ping Pong Results</h1>
      <?php foreach ($output as $key => $value) {
            echo $value.',';
      } ?>
  </body>
</html>

答案 1 :(得分:1)

您运行打印到屏幕的 pingpong()功能 var $ output = NULL

<?php
$input = $_GET["number"];
$range = range(0, $input);
**$output = pingpong($range); **  (the problem here)

function pingpong($fx_range)
{
  foreach ($fx_range as $number) {
    **echo $number . ", ";**  (the problem here)
  }
}
?>


<!DOCTYPE html>
<html>

你应该把它放到变量或数组

我会采用不同的方式:

<?php
$input = $_GET["number"];
$range = range(0, $input);
$output = pingpong($range);

function pingpong($fx_range)
{
  foreach ($fx_range as $number) {
    $var[] = $number;
  }
  return $var;
}
?>


<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Ping Pong</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css">
  </head>
  <body>
    <div class="container">
      <h1>Ping Pong Results</h1>
      <?= implode(', ',$output) ?>
  </body>
</html>

内爆,你最终没有“,”得到更清晰的结果。 而且您不需要运行多个循环 如果你想要有不同的排序输出,你可以使用数组排序功能轻松完成。