PHP回声中回声

时间:2018-06-13 08:01:31

标签: php echo

我有一个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行的?

6 个答案:

答案 0 :(得分: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];

并且说,通过显式索引连接数组中的所有内容是非常冗长的。有一个专门为此设计的功能。

$posts = implode($post_single);

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

答案 1 :(得分:1)

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

$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] ."";

答案 2 :(得分:0)

这样做:

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

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

答案 3 :(得分:0)

循环怎么样?像这样的东西

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

答案 4 :(得分:0)

取代这个:

$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]}";

答案 5 :(得分:0)

而不是:

$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>