【发布时间】:2018-03-15 15:24:22
【问题描述】:
我将一些 json 格式的数据发布到 php 脚本中,这些数据需要替换会话(数组)中的现有数据。
这是我发布到我的 PHP 脚本的内容:
Array
(
[0] => stdClass Object
(
[product] => Bad 1
[quantity] => 2
)
[1] => stdClass Object
(
[product] => Bad 14
[quantity] => 1
)
)
这是我的会话数组 ($_SESSION['cart']):
Array
(
[Bad 1] => Array
(
[artikelid] => 2
[product] => Bad 1
[price] => 1000
[picture] => cms/images/bad.jpg
[quantity] => 2
[alias] => bad1
[catalias] => baden
)
[Bad 14] => Array
(
[artikelid] => 11
[product] => Bad 14
[price] => 800
[picture] => images/defaultimage.jpg
[quantity] => 1
[alias] => bad-14
[catalias] => baden
)
)
我希望发布的数量值替换会话数组中的数量值,但仅限于正确的产品。因此,如果我使用产品“bad 1”发布数量“10”,则只需将键“bad 1”的数量替换为该值。
在我的示例中发布多个产品时也会出现这种情况(发布的对象)。
如何将对象更改为数组并将其与会话数组合并(仅替换数量)?
我尝试过类似的方法,但这仅适用于一个发布值。
//Wanneer er een post waarde is vanaf het ajax script:
if($_POST['product']){
//Stop de productnaam in de variabele $prod
$prod = $thisProduct['product'] ;
//Als er nog geen sessie bestaat, maak deze dan aan
if (!isset($_SESSION['cart'])) {
//en maak er gelijk een array van
$_SESSION['cart'] = [];
}
//Als de productnaam nog niet voorkomt in de sessie, voeg deze dan toe inclusief de overige array waarden
if (!isset($_SESSION['cart'][$prod])) {
$_SESSION['cart'][$prod] = $thisProduct;
}
//Als deze wel voorkomt voeg hem dan niet toe maar tel de quantity op bij het bestaande product
else {
$_SESSION['cart'][$prod]['quantity'] += $thisProduct['quantity'];
}
}
我在 Don't Panic 的帮助下修复了这个问题:
$quantityobject = $_POST['quantityobject'];
$arrayquantity = json_decode($quantityobject);
foreach ($arrayquantity as $object) {
// Check if product exists in array
if (isset($_SESSION['cart'][$object->product])) {
// if so replace quantity with posted one
$_SESSION['cart'][$object->product]['quantity'] = $object->quantity;
}
}
【问题讨论】:
-
首先您必须编写一些代码。您是否尝试过编写任何代码?
-
这看起来并不棘手,特别是因为会话已经使用产品作为其密钥。
-
您可能将 SO 误认为是免费使用的编码服务。 我们不是,但如果你待的时间足够长,Rep Hound 很快就会出现
-
@RiggsFolly 我得到了类似的东西,添加到数组中,但这只会发布一个值,并检查它是否存在于数组中。我会在我的问题中添加它。但我被困在如何用另一个数组/对象来做到这一点。
-
那你需要写一个循环