如何将多个值保存到数组中并一起检索它们

问题描述 投票:0回答:1

我正在使用PHP制作聊天框,基本上我不想使用任何数据库和表来存储和检索此聊天框的数据。我想做的就是创建一个发送的消息数组,然后以图形方式显示该数组的值。像这样的东西:

用户:

  message 1 

  message 2

  message 3

正如您所看到的,用户可以编写新消息,当他单击“发送”按钮时,必须创建一个数组并存储他在其中写入的消息。

如果用户输入了新内容并重新发送,则应保存新值,同时保留以前的消息。

因此,通过这种方式,我可以在聊天框中创建一个For循环并检索用户已发送的所有消息。

我试过这段代码:

 if (isset($_POST['send'])){
        $pm = $_POST['message'];
        $bot_pms[] = $pm;
        $sent = file_get_contents($website."/sendmessage?chat_id=$id&text=$pm");
        print_r($bot_pms);
  }
  echo '
        <div class="box-footer">
                <form action="" method="post">
                    <div class="input-group">
                    <input type="text" name="message" placeholder="Write your direct message" class="form-control">
                    <span class="input-group-btn">
                    <input name="send" type="submit" class="btn btn-danger btn-flat"/></span>
                    </div>
                 </form>
        </div>
';

这是用于发送消息。为了显示消息,我做了这个:

$num3 = count($bot_pms);
for($z=0;$z<$num3;$z++){
        echo '<div class="direct-chat-text">';
        echo $bot_pms[$z];
        echo '</div>';
}

但问题是,它不保存以前的消息,它只是重写该数组的值。我认为使用Session Variables,这个功能可以完成,但我不知道怎么做!

所以,如果您知道如何在PHP中执行此操作,请告诉我... thx

更新(会话方式):

我想知道这种方式是对还是错?

if (isset($_POST['send'])){
$_SESSION['messages'] = $_POST['message'];
$sent = file_get_contents($website."/sendmessage?chat_id=$id&text=$pm");
print_r($_SESSION);
}

和:

$num3 = count($_SESSION);
for($z=0;$z<$num3;$z++){
echo '<div class="direct-chat-text">';
echo $_SESSION['messages']; 
echo '</div>';
}
php arrays
1个回答
-1
投票
 if (session_status() == PHP_SESSION_NONE) {
     session_start();
     $_SESSION['messages'] = array();  }

 if(isset($_POST['send'])) {
     array_push($_SESSION['messages'], $_POST['send']);  }
© www.soinside.com 2019 - 2024. All rights reserved.