【问题标题】:PHP echo array?PHP回显数组?
【发布时间】:2017-02-06 13:09:10
【问题描述】:

我是新手,不知道如何填充数组并回显它。有人可以帮帮我吗? :)

首先我的数组,我希望从我的 notes.txt 文件中检索信息,如果有的话?!我不确定我是否需要两个声明?:

$test = array();
$test[] = json_decode(file_get_contents($file), TRUE);

不管怎样,这是向数组添加元素的代码,来自用户的输入:

$name = guestbook_input($_POST['name']);
$comment = guestbook_input($_POST['comment']);

$test[] = [
    'name' => $name,
    'comment' => $comment,
    'ip' => $_SERVER['REMOTE_ADDR'],
    'time' => date("y-m-d H:m")
];

// Write input to file
file_put_contents($file, json_encode($test));

这段代码工作正常(我认为)并写入文件。

最后我试图将数组回显到这样的表中:

<?php
$getfile = json_decode(file_get_contents('./notes.txt'), TRUE);
        foreach ($getfile as $value):   ?>
        <tr>
            <?php
                echo '<td>';
                echo $value['name'];
                echo '</td>';
                echo '<td>';
                echo $value['comment'];
                echo '</td>';
                echo '<td>IP:';
                echo $value['ip'];
                echo "<br>Tid:";
                echo $value['time'];
                echo '</td>'?>

        </tr>  <?php    endforeach; ?>

此代码打印元素,但仅用于我留言簿中的第一个输入。我不知道这是否是正确的方法,但希望有人可以帮助我,这样我就可以做到这一点?!

【问题讨论】:

  • 看看 file_put_contents 和第三个参数 FILE_APPEND ...
  • 在您的问题中向我们展示 print_r($getfile),
  • 我没有 print_r($getfile)。也许这就是问题所在?
  • 您在 notes.txt 文件中得到了什么?你能用你的问题更新它吗
  • 在您的date 函数中,您应该使用i 几分钟。 m 是几个月。

标签: php arrays forms input foreach


【解决方案1】:

首先,你的声明和赋值:

$test = array();
$test[] = json_decode(file_get_contents($file), TRUE);

函数json_decode(),当您调用它时,它返回一个数组,因此不需要首先声明变量,但这样做是一个好习惯。但是,在函数调用中,您实际上是将整个结果分配给 $test[0],因为 $test[] 只是创建一个具有下一个数字索引的新元素。您分配用户输入的代码是正确的,因此可以正确输出。

【讨论】:

    【解决方案2】:

    您将从文件中读取的数组放入数组 $test 的单个元素中。
    然后,您将添加新条目作为第二个元素。

    您应该将数组初始化为:

    $test = json_decode(file_get_contents($file), TRUE);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-23
      • 1970-01-01
      相关资源
      最近更新 更多