【问题标题】:PHP echo within an echo回声中的 PHP 回声
【发布时间】:2018-06-13 08:01:31
【问题描述】:

我有一个 php 脚本来回显每页一定数量的帖子:

<div class="posts">
    <?php echo $post[1]; ?>
    <?php echo $post[2]; ?>
    <?php echo $post[3]; ?>
    <?php echo $post[4]; ?>
</div>

这很好用,但我想将数据保存在单独的 php 部分中,然后使用简单的语句将其回显。所以为此我创建了:

$posts = "".$post_single[1];$post_single[2];$post_single[3];$post_single[4];."";  // Error On This Line

<div class="posts">
    <?php echo $posts; ?>
</div>

当我运行它时,我收到错误 Parse error: syntax error, unexpected '.' in ...

有什么想法可以解决这个问题以正确回显$posts 行吗?

【问题讨论】:

标签: php echo


【解决方案1】:

; 表示语句结束。 . 连接两个字符串。你把两者混淆了。

$posts = "" . $post_single[1] . $post_single[2] . $post_single[3] . $post_single[4] . "";

也就是说,将空字符串连接到开头和结尾是没有意义的。所以不要那样做。

$posts = $post_single[1] . $post_single[2] . $post_single[3] . $post_single[4];

也就是说,通过显式索引连接数组中的所有内容非常冗长。有一个为此设计的函数。

$posts = implode($post_single);

请注意,这还将包括您忽略的$post_single[0]

【讨论】:

  • 谢谢。这个解决方案效果很好,虽然我不能使用implode 版本,因为$single_post[0] 在页面中被进一步使用,因此在$posts 字符串中不需要
【解决方案2】:

你没有正确回显,你需要连接每个变量,例如:

$stringOne = 'hello';
$stringTwo = 'world';

echo $stringOne. ' ' .$stringTwo; # this will output hello world;

所以在你的情况下:

$posts = "".$post_single[1];$post_single[2];$post_single[3];$post_single[4];."";

应该是

$posts = "".$post_single[1]. $post_single[2]. $post_single[3]. $post_single[4] ."";

【讨论】:

    【解决方案3】:

    这样做:

    $posts = "".$post_single[1]."".$post_single[2]."".$post_single[3]."".$post_single[4];
    
    <div class="posts">
        <?php echo $posts; ?>
    </div>
    

    【讨论】:

      【解决方案4】:

      循环怎么样?像这样的

      <div class="posts">
          <?php 
             foreach ($posts as $post) {
               echo $post;
             }
           ?>
      </div>
      

      【讨论】:

        【解决方案5】:

        代替这个:

        $posts = "".$post_single[1];$post_single[2];$post_single[3];$post_single[4];."";
        

        试试这个:

        $posts = $post_single[1].$post_single[2].$post_single[3].$post_single[4];
        

        或者这个:

        $posts = "{$post_single[1]}{$post_single[2]}{$post_single[3]}{$post_single[4]}";
        

        【讨论】:

          【解决方案6】:

          而不是这个:

          $posts = "".$post_single[1];$post_single[2];$post_single[3];$post_single[4];."";
          

          试试这个:

          $posts = "".$post_single[1] . $post_single[2] . $post_single[3] . $post_single[4]."";
          

          使用 . 运算符连接变量。

          <div class="posts">
              <?php echo $posts; ?>
          </div>
          

          【讨论】: