我收到此错误:
"Warning: array_merge(): Argument #1 is not an array in
C:\xampp\htdocs\sam\arraysession.php on line 16"
但具有讽刺意味的是这个例子来自书中...... 并且没有输入错误,我检查了几次。 有人可以给我一个提示吗?我真的很沮丧......
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<head>
<title>Storing an array with a session</title>
</head>
<body>
<h1>Product choice page</h1>
<?php
if (isset($_POST['form_products'])) {
if(!empty($_SESSION['products'])) {
echo $_SESSION['products'];
$products = array_unique(
array_merge(unserialize($_SESSION['products']), $_POST['form_products']));
} else {
$_SESSION['products'] = $_POST['form_products'];
}
echo "<p>Your products have been registered!</p>";
}
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<p><label for="form_products">Select some products:</label><br>
<select id="form_products" name="form_products[]" multiple="multiple"
size = "3">
<option value="Sonic Screwdriver">Sonic screwdriver</option>
<option value="Hal 2000">Hal 2000</option>
<option value="Tardis">Tardis</option>
<option value="ORAC">ORAC</option>
<option value="Transporter bracelet">Transporter bracelet</option>
</select></p>
<button type="submit" name="submit" value="choose">Submit form</button>
</form>
<p><a href="session1.php">go to content page</a></p>
</body>
</html>
$ _ SESSION ['products']包含
a:3:{i:0;s:17:"Sonic Screwdriver";i:1;s:8:"Hal 2000";i:2;s:6:"Tardis";}
var_dump $ _SESSION ['products']显示
string(71) "a:3:{i:0;s:17:"Sonic Screwdriver";i:1;s:8:"Hal 2000";i:2;s:6:"Tardis";}"
反序列化($ _ SESSION [ '产品']);包含
Array
(
[0] => Sonic Screwdriver
[1] => Hal 2000
[2] => Tardis
)
答案 0 :(得分:0)
当您对$_SESSION['products']
进行反序列化时,它应该包含一个字符串。因此,当您将值存储到其中时,请存储已发布数组的已筛选形式。
你必须这样做
if (isset($_POST['form_products'])) {
if(!empty($_SESSION['products'])) {
$products = array_unique(
array_merge(unserialize($_SESSION['products']), $_POST['form_products']));
$_SESSION['products'] = serialize($products);
} else {
$_SESSION['products'] = serialize($_POST['form_products']);
}
echo "<p>Your products have been registered!</p>";
}