Hello我通过$ _POST收到一个user_name和一个user_id。
我希望在$ _SESSION中获得类似的东西:
(id) - (user_name)
5 - John
6- Paul
<?php
$user_id = $_POST['user_id'];
$user_name = $_POST['user_name'];
$_SESSION['test'] = array('user_id' => $user_id, 'user_name' => $user_name);
foreach( $_SESSION['test'] as $key => $value )
{
echo $key;
echo $value;
}
?>
仅显示John和他的id。我的意思是保罗和他的身份不显示。为什么?
我有一个js脚本,
$.ajax({
url : "ajax_chat.php",
type: "POST",
data: 'action='+action+'&user_id='+user_id,
success: function(result)
{
}
});
当有人点击某个用户时,我希望为每个id创建一个会话,并将其发送到我的php文件。
ajax_chat.php
if ($action == "ChangeSessionValueUser")
{
$_SESSION['test'] = array('user_id' => $user_id, 'user_name' => $user_name);
}
index.php中的
<?php
foreach( $_SESSION['test'] as $key => $value )
{
echo $key;
echo $value;
}
?>
答案 0 :(得分:1)
您没有正确理解数组。在没有会话的情况下采用更简单的代码:
$test = array('user_id' => 5, 'user_name' => 'john');
$test = array('user_id' => 6, 'user_name' => 'paul');
print_r($test);
// this only prints paul, since you've overwritten the variable.
// You want an array of arrays instead, so
$test = array();
$test[] = array('user_id' => 5, 'user_name' => 'john');
$test[] = array('user_id' => 6, 'user_name' => 'paul');
print_r($test);
// this prints out both
// If you want to loop, you must change it a little bit
foreach ($test as $value) {
echo 'User ' . $value['user_name'] . ' with user id ' . $value['id'];
}
// if you do echo($value); this yields "Array"
// since you have an array in an array.
要仅在会话中初始化一次数组,您可以使用类似
的内容if (!isset($_SESSION['test'])) {
$_SESSION['test'] = array();
}
// then you can push in additional users on all pages like
$_SESSION['test'][] = array('id' => 7, 'user_name' => 'test');
// and output all with
foreach ($_SESSION['test'] as $value) {
echo 'User ' . $value['user_name'] . ' with user id ' . $value['id'];
}
答案 1 :(得分:1)
我可能会误解你在做什么。但是,如果每个POST请求只获得一个 user_id
和一个 user_name
,那么您需要做一些事情要做。
您需要添加session_start()
来激活或重新启动会话,这是一个简单的资源:http://www.w3schools.com/php/php_sessions.asp
$_SESSION['test'] = array('user_id' => $user_id, 'user_name' => $user_name);
您每次都会覆盖$_SESSION['test']
变量。因此,您需要将新数组附加到“测试”的末尾。像这样$_SESSION['test'][] = array(...)
(如果我理解你想做什么)所以你的代码应该是这样的:
<?php
session_start();
$user_id = $_POST['user_id'];
$user_name = $_POST['user_name'];
$_SESSION['test'][] = array('user_id' => $user_id, 'user_name' => $user_name);
foreach( $_SESSION['test'] as $key => $value )
{
echo $key;
echo $value;
}
?>
这应该在每次向&#34; test&#34;下的$ _SESSION全局给一个时添加一个user_id和user_name对。键。
答案 2 :(得分:0)
您正在从POST收到一个值。您需要为每个输入字段设置数组名称,如:
<input type="text" name="user_id[]" />
<input type="text" name="user_name[]" />
然后,当您收到这些值时,将它们逐个放入会话中:
$_SESSION['test'] = array();
foreach ($_POST['user_id'] as $i => $id) {
$_SESSION['test'][] = array($id => $_POST['user_name'][$i]);
}