gpt4 book ai didi

php - 我是否走在简化 php 代码块的正确道路上?

转载 作者:行者123 更新时间:2023-11-29 19:10:29 25 4
gpt4 key购买 nike

对 php 相当陌生,正在学习电子商务教程。在探索解决 php 代码块问题的方法时,我发现了另一个人使用相同代码块的帖子。 https://forums.phpfreaks.com/topic/272404-help-problem-with-some-line-of-codes/ 这篇文章提出了一种简化代码的方法。

原始代码块:

   <?php
if (isset($_POST ['pid'])) {
$pid = $_POST ['pid'];
$wasFound = false;
$i = 0;
if (!isset ($_SESSION["cart_array"]) || count($_SESSION ["cart_array"])<1){
$_SESSION["cart_array"] = array (0=> array("item_id"=> $pid, "quantity" => 1));
} else {
foreach ($_SESSION["cart_array"] as $each_item) {
$i++;
while(list($key,$value)=each($each_item)){
if ($key== "item_id" && $value == $pid) {
array_splice ($_SESSION["cart_array"], $i-1,1, array(array("item_id"=>$pid,"quantity"=> $each_item['quantity']+1)));
$wasFound = true;
}
}
}
if($wasFound==false) {
array_push ($_SESSION["cart_array"], array("item_id"=> $pid, "quantity" => 1));
}
}
header("Location: cart.php");
exit();
}
?>

这是建议的简化代码块以及更改代码后要执行的操作的说明。我不确定如何实现代码块后建议的部分。

if (isset($_POST['pid'])) {
// add (+1) item to cart
$pid = (int)$_POST['pid']; // cast as integer
// valid pids are > 0
if($pid > 0){
if(!isset($_SESSION['cart_array'][$pid])){
// item is not in the cart, add it with quantity = 1
$_SESSION['cart_array'][$pid] = array("item_id" => $pid, "quantity" => 1); // I left the array in the cart the same, but it could also be simplified so that it is only the quantity, since the item_id is now the cart array index
} else {
// item is in the cart, increment quantity
$_SESSION['cart_array'][$pid]['quantity']++;
}
}
header("location: cart.php");
exit();
}

要获取购物车商品的详细信息,您需要运行一个查询来同时获取所有商品(将查询放入循环内会造成资源 killer 。)对于我所拥有的购物车的定义建议,您可以使用 array_keys 来获取所有项目 id。然后,您可以将它们分解为逗号分隔的列表,并将它们放入查询中 WHERE 子句中的 IN() 比较中,以一次获取所有匹配的行。PFMaBiSmAd 编辑,2012 年 12 月 27 日 - 下午 02:05。

这是我正在考虑添加到代码块中的内容:

if  ($result = print_r(array_keys('cart_array',$pid))) {
$comma_seperated = implode("," $result);

// then use use $comma_seperated in query where needed later in annother code block?
}

我走的路正确吗?

最佳答案

这是由 Mike Brant 在 codereview.stackexchange 中提供的。这就是我提取要在查询中使用的键的方法。

$pidsInCart = array_keys($_SESSION['cart_array']);

关于php - 我是否走在简化 php 代码块的正确道路上?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43122693/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com