【发布时间】:2013-04-21 03:43:51
【问题描述】:
我有这个代码用于我的学校项目,并认为代码可以按照我想要的方式完成工作,但在使用 array_replace() 和array_merge()函数:
会话已在标头上启动:
// Start Session
session_start();
将$_SESSION['cart'] 初始化为数组:
// Parent array of all items, initialized if not already...
if (!isset($_SESSION['cart'])) {
$_SESSION['cart'] = array();
}
从下拉菜单中添加产品:-(只是看看会话是如何分配的:)
if (isset($_POST['new_item'])) { // If user submitted a product
$name = $_POST['products']; // product value is set to $name
// Validate adding products:
if ($name == 'Select a product') { // Check if default - No product selected
$order_error = '<div class="center"><label class="error">Please select a product</label></div>';
} elseif (in_array_find($name, $_SESSION['cart']) == true) { // Check if product is already in cart:
$order_error = '<div class="center"><label class="error">This item has already been added!</label></div>';
} else {
// Put values into session:
// Default quantity = 1:
$_SESSION['cart'][$name] = array('quantity' => 1);
}
}
那么当他们尝试更新产品时,问题就出现了:
// for updating product quantity:
if(isset($_POST['update'])) {
// identify which product to update:
$to_update = $_POST['hidden'];
// check if product array exist:
if (in_array_find($to_update, $_SESSION['cart'])) {
// Replace/Update the values:
// ['cart'] is the session name
// ['$to_update'] is the name of the product
// [0] represesents quantity
$base = $_SESSION['cart'][$to_update]['quantity'] ;
$replacement = $_SESSION['cart'][$to_update] = array('quantity' => $_POST['option']);
array_replace($base, $replacement);
// Alternatively use array merge for php < 5.3
// array_merge($replacement, $base);
}
}
请注意,array_replace() 和 array_merge() 两个函数都在更新值并执行最初的目标,但问题是我仍然继续获取那个参数($base)不是数组问题.
警告:array_replace() [function.array-replace]:参数 #1 不是...中的数组
任何有关解决此问题的更好方法的建议都将是宝贵的帮助:) 谢谢你的帮助:)
编辑:in_array_find() 是我用来替换 in_array() 的函数,因为它不适用于在多维数组中查找值:特别是 2 个深度数组:
从 here 找到它,它对我有用
它的代码是:
// Function for searching values inside a multi array:
function in_array_find($needle, $haystack, $strict = false) {
foreach ($haystack as $item => $arr) {
if (($strict ? $item === $needle : $item == $needle) || (is_array($item) && in_array_r($needle, $item, $strict))) {
return true;
}
}
return false;
}
【问题讨论】:
-
我不熟悉
in_array_find()。这是您自己的功能还是您的意思是in_array()? -
谢谢。 @showdev 我已经添加了该函数的代码 :),我正在使用它来替换多维数组的
in_array()。 -
明白了,谢谢。如果你在错误之前
echo"<pre>";print_r($_SESSION);echo"</pre>";,你会得到什么? -
首先我在没有提交时得到这个
[cart] => Array()= 用于购物车,当我更新值时我得到这个( [quantity] => 1 )))= 出现错误的地方。 - 它确实更新了购物车并替换了值,但也出现了上述错误,认为购物车已更新 -
你在页面顶部做
session_start()吗?
标签: php arrays session session-variables