编辑JSON文件

时间:2017-11-07 09:59:56

标签: javascript php angularjs json

首先是的,我确实检查了其他选项,问题和答案,但遗憾的是那些对我不起作用。

所以我目前正在开发一个包括购物车系统的小项目。 购物车系统是由PHP会话创建的,一切正常。可以添加产品,删除行,并可以完全清除购物车。

现在我想添加一些功能,比如计算购物车中的商品,计算总价和增值税价格。由于会话存储为JSON对象,因此我可以使用angularjs$http.get()来读取JSON购物车对象并重新定义数据,以便它可以在ng-repeat中使用对于观点。

因此,当访问者点击“添加到购物车”按钮时,以下代码正在创建会话:

session_start();

$product_id = $_REQUEST['product_id'];
$product_name = $_REQUEST['product_name'];
$product_price = round($_REQUEST['product_price'], 2);
$product_size = $_REQUEST['product_size'];
$product_quantity = $_REQUEST['product_quantity'];
$total_product_price = $product_price*$product_quantity;
round($total_product_price, 2);
// Add new item to session
$cartProduct = array(
    "id" => $product_id,
    "name" => $product_name,
    "price" => $product_price,
    "size" => $product_size,
    "quantity" => $product_quantity,
    "total_product_price" => $total_product_price,
    "total_items" => 0
);

/*
 * check if the 'cart' session array was created
 * if it is NOT, create the 'cart' session array
 */
if(empty($_SESSION['cart']["cartItems"])){
    $_SESSION['cart']["cartItems"] = array();
}

// check if the item is in the array, if it is, do not add
if(array_key_exists($product_id and $product_size, $_SESSION['cart'])){
    // redirect to product list and tell the user it was added to cart
    echo "<script> alert('Dit product staat al in de winkelwagen')</script>])";
}

// else, add the item to the array
else{
    $_SESSION['cart']["cartItems"][$product_id]=$cartProduct;
}

所以我的第一次尝试是将以下内容添加到“将项目添加到数组”

部分
    $arr = json_decode($_SESSION['cart']['cartItems'][$product_id], true);
    $total_items['total_items'] = count($_SESSION['cart']);
    array_push($arr['cartItems'], $total_items);

但遗憾的是,这不起作用。我也尝试将其添加到getCart部分。

session_start();

$json = json_encode($_SESSION['cart']["cartItems"]);
echo($json);

可悲的是,也没有任何结果。

所以我的问题是如何将total_items计算添加到数组中。我如何计算总价,增值税价格等?

PS:一种产品的JSON结果:

{"16":{"id":"16","name":"TestDatumProduct","price":1000,"size":"M","quantity":"4","total_product_price":4000,"total_items":0}}

更新

这是一个结合过去几天进展的更新:

所以目前我的代码是基于@devionNL的答案,因为我喜欢动作方法而且@FranciscoRodríguez的答案几乎没有答案,因为他只是向我推荐了计数方法,(没有用)

因此,使用@devionNL中的动作示例,我做了一些小改动,并提出了以下代码。

<?php
session_start();
$cartItemID = $_REQUEST['cartItem_id'];
$product_id = $_REQUEST['product_id'];
$product_name = $_REQUEST['product_name'];
$product_price = round($_REQUEST['product_price'], 2);
$product_size = $_REQUEST['product_size'];
$product_quantity = $_REQUEST['product_quantity'];
$total_product_price = $product_price*$product_quantity;
round($total_product_price, 2);

// Add new item to session
$cartProduct = array(
    "id" => $product_id,
    "name" => $product_name,
    "price" => $product_price,
    "size" => $product_size,
    "quantity" => $product_quantity,
    "total_product_price" => $total_product_price
);

// If the session is empty create an empty array
if(empty($_SESSION['cart']["cartItems"])){
    $_SESSION['cart']["cartItems"] = array();
}

// Add to cart
if ($_REQUEST['action'] == 'addToCart')
{
    if (array_key_exists($product_id, $_SESSION['cart']['cartItems']))
    {
        $_SESSION['cart']['cartItems']['totalItems']++;
    }
    else
    {
        $_SESSION['cart']['cartItems']['totalItems']++;
        array_push($_SESSION['cart']['cartItems'], $cartProduct );
    }
}

// RemoveRow
else if ($_REQUEST['action'] == 'removeRow') // If you want a delete action
{
    if (array_key_exists($product_id, $_SESSION['cart']['cartItems']))
    {
        if ($_SESSION['cart']['cartItems']['totalItems'] > 1)
        {
            foreach ($cartDecode as $key => $cartItem)
            {
                // IF THE TITLE MATCHES THE SIGNAL STRING
                if ($cartItem->{"id"} == $cartItemID)
                {
                    // REMOVE THIS OBJECT
                    unset($cartDecode[$key]);
                }

            }
            $_SESSION['cart']['cartItems']['totalItems']--; // Deduct by 1.
        }
    else
        {
            $_SESSION['cart']['cartItems'] = $cartProduct;
        }
    }

    $_SESSION['cart']['cartItems']['totalPrice'] = array_sum(array_map(function($item) {
        return $item['price'] * $item['totalItems'];
    },
        $_SESSION['cart']['cartItems']));

}
$cart = json_encode($_SESSION['cart']['cartItems']);
echo ($cart);

因此添加到购物车,并计算cartItems正在按预期工作。但我仍然找不到删除行的方法。在车内。接下来,我仍然在努力获得cart的总价。 JSON结果如下:

{"totalItems":2,"0":{"id":"7","name":"Bedrukt jurkje van chiffon","price":20.5,"size":"M","quantity":"3","total_product_price":61.5},"1":{"id":"5","name":"Bedrukte Zomerjurk","price":30.5,"size":"M","quantity":"3","total_product_price":91.5}}

JSON中的完整购物车将是:

{"cartItems":{"totalItems":2,"0":{"id":"7","name":"Bedrukt jurkje van chiffon","price":20.5,"size":"M","quantity":"3","total_product_price":61.5},"1":{"id":"5","name":"Bedrukte Zomerjurk","price":30.5,"size":"M","quantity":"3","total_product_price":91.5}}}

所以我的问题是? 1.如何删除单行(ID == "", Then delete) 2.我如何计算购物车的全价? 3.为了将订单放在dabatase中,我如何能够选择每一行? (id,name等)。我在考虑使用foreach()语句?

如果有任何问题,请在评论中询问。

一如既往,提前致谢!

4 个答案:

答案 0 :(得分:2)

乍一看,我可以看到一些奇怪的东西在这里:

$arr = json_decode($_SESSION['cart']['cartItems'][$product_id], true);
$total_items['total_items'] = count($_SESSION['cart']);
array_push($arr['cartItems'], $total_items);

您正在$arr存储1个单品的json对象。然后在计算总数(实际上是在计算购物车根数组的大小)后,尝试将其存储在键'total_items'的数组中。最后,您尝试将整个数组附加到json对象,键'cartItems'(也不是产品的键)

我认为你要做的只是这样:

$_SESSION['cart']['cartSize'] = count($_SESSION['cart']['cartItems']);

答案 1 :(得分:1)

最好的方法是将您的产品信息存储在数据库中,而不是让客户端将所有信息发送到服务器,因为您最初无法验证客户端是否说实话(阅读:永远不要信任客户端输入)。

基本上客户端应该发送的只是添加/删除和它想要添加的productId,你可以然后返回价格等的完整对象,但客户端不应该能够更新& #39;那个价格。

这假设$ product_id包含要添加或删除的产品。

session_start();

// If the cart or cartItems isn't set, create empty
if (empty($_SESSION['cart']) || empty($_SESSION['cart']['cartItems']))
{
   $_SESSION['cart'] = array();
   $_SESSION['cart']['cartItems'] = array();
   $_SESSION['cart']['totalPrice'] = 0;
   $_SESSION['cart']['totalItems'] = 0;
}

// Search the cartItems for the column named productId that matches the $product_id. This can return null, so always verify with !empty.

$arrayKeyId = array_search($product_id, array_column($_SESSION['cart']['cartItems'], 'productId'));

if ($_REQUEST['action'] == 'add')
{
  if (!empty($arrayKeyId)) // If it isn't empty, append to  the quantity
     $_SESSION['cart']['cartItems'][$arrayKeyId]['totalItems']++;
  else // It's new: Add it to the array
     $_SESSION['cart']['cartItems'][] = $cartProduct;
}
else if ($_REQUEST['action'] == 'delete') // If you want a delete action
{
  if (!empty($arrayKeyId))
  {
   // If more than 1 quantity, lower by 1 
   if ($_SESSION['cart']['cartItems'][$arrayKeyId]['totalItems'] > 1)
       $_SESSION['cart']['cartItems'][$arrayKeyId]['totalItems']--;
   else // Or if there was only 1, remove the item fully. 
      unset($_SESSION['cart']['cartItems'][$arrayKeyId]);
  }
}

// Total price based on item count times their price.
$_SESSION['cart']['totalPrice'] = array_sum(array_map(function($item) { 
    return $item['price'] * $item['totalItems']; 
}, $_SESSION['cart']['cartItems']));

// Total items based on the total amount of cartItems (without their quantity)
$_SESSION['cart']['totalItems'] = count($_SESSION['cart']['cartItems']);


echo json_encode($_SESSION['cart']['cartItems']);

答案 2 :(得分:1)

我在这里有点失落所以请原谅我,如果我错了,希望它有预期的结果:

<?php
session_start();
//unset($_SESSION['cart']);
var_dump($_SESSION['cart']['cartItems']);
$cartItemID = $Req['cartItem_id'];
$product_id = $Req['product_id'];
$product_name = $Req['product_name'];
$product_price = round($Req['product_price'], 2);
$product_size = $Req['product_size'];
$product_quantity = $Req['product_quantity'];
$total_product_price = $product_price*$product_quantity;
round($total_product_price, 2);

// Add new item to session
$cartProduct = array(
    "id" => $product_id,
    "name" => $product_name,
    "price" => $product_price,
    "size" => $product_size,
    "quantity" => $product_quantity,
    "total_product_price" => $total_product_price
);

// If the session is empty create an empty array
if(empty($_SESSION['cart']["cartItems"])){
    $_SESSION['cart']["cartItems"] = array();
    $_SESSION['cart']["cartItems"]["totalitems"] = 0;
    $_SESSION['cart']["cartItems"]["totalprice"] = 0;

}

// Add to cart
if ($Req['action'] == 'addToCart') {
    if (!isset($_SESSION['cart']["cartItems"][$cartItemID])) {
        $_SESSION['cart']["cartItems"][$cartItemID] = $cartProduct;
        $_SESSION['cart']["totalitems"]++;
        $_SESSION['cart']["totalprice"] += $total_product_price;
    }
}

// RemoveRow
else if ($Req['action'] == 'removeRow') // If you want a delete action
{
    if (isset($_SESSION['cart']["cartItems"][$cartItemID])) {
        $_SESSION['cart']["totalitems"]--;
        $_SESSION['cart']["totalprice"] -= $_SESSION['cart']["cartItems"][$cartItemID];
        unset($_SESSION['cart']["cartItems"][$cartItemID]);
    }

}
$cart = json_encode($_SESSION['cart']['cartItems']);
echo ($cart);

所以解释一下。使用&#34; cartItemID&#34;作为&#34; cartProduct&#34;的关键。在&#34; cart&#34;中还有两个关键词。总项目数和总价格的数组。并回答你的问题:

  • 购物车的总价格将在&#34; $ _ SESSION [&#39; cart&#39;] [&#34; totalprice&#34;]&#34;

    < / LI>
  • 要将它们插入数据库,您只需预约$ _SESSION [&#39; cart&#39;] [&#34; cartItems&#34;]数组。

答案 3 :(得分:0)

好的,我相信我至少可以使用我的测试数据。我已经在代码的每一点上发表评论,我认为这需要改变。另请注意,totalItems和totalPrice必须位于$ _SESSION ['cart']和$ _SESSION ['cart'] [“cartItems”]必须只保留items数组elese array_map函数,你要使得总和不会工作。希望对你有所帮助。

session_start();
    $cartItemID = $_REQUEST['cartItem_id'];
    $product_id = intval($_REQUEST['product_id']); //if product_id is integer use intval
    $product_name = $_REQUEST['product_name'];
    $product_price = round(doubleval($_REQUEST['product_price']), 2);//if product_price is double use doubleval will help for the calculations
    $product_size = $_REQUEST['product_size'];
    $product_quantity = intval($_REQUEST['product_quantity']); //if product_quantity is integer use intval will help for the calculations
    $total_product_price = $product_price*$product_quantity; 
    round($total_product_price, 2);



    // Add new item to session
    $cartProduct = array(
        "id" => $product_id,
        "name" => $product_name,
        "price" => $product_price,
        "size" => $product_size,
        "quantity" => $product_quantity,
        "total_product_price" => $total_product_price
    );

    // If the session is empty create an empty array
    if(empty($_SESSION['cart']["cartItems"])){
        $_SESSION['cart']["cartItems"] = array();
    }

    // Add to cart
    if ($_REQUEST['action'] == 'addToCart')
    {
        if (array_key_exists($product_id, $_SESSION['cart']['cartItems']))
        {
            //$_SESSION['cart']['totalItems']++; //this line can cause problems when removing item out of the cart, when the user adds an item and you increment the total items value, you have to increment the value for the specific product in order to substract the correct number in the removal, 
            //you can use 2 approaches depending what you trying to achieve, 
            //1. if $_SESSION['cart']['totalItems'] is the items by type then you don't need to increment if item exists , just comment your line
            //2. if $_SESSION['cart']['totalItems'] represents the total number of items by adding the quantity of every product then this has to change use the following which i recommend
            $_SESSION['cart']['cartItems'][$product_id]['quantity']+=$product_quantity;
            $_SESSION['cart']['cartItems'][$product_id]['total_product_price']+=$total_product_price;
        }
        else
        {
            //$_SESSION['cart']['totalItems']++;
            //use this line for 2nd apporach
            $_SESSION['cart']['cartItems'][$product_id] = $cartProduct ; //array_push is wrong here you need a key that is the product id not the next available index, array_push will just give you the next available index, that's why the rest not working

        }
        //use this line for 2nd apporach
        $_SESSION['cart']['totalItems']+=$product_quantity;
    }

    // RemoveRow
    else if ($_REQUEST['action'] == 'removeRow') // If you want a delete action
    {
        if (array_key_exists($product_id, $_SESSION['cart']['cartItems']))
        {
            if ($_SESSION['cart']['totalItems'] > 1)
            {
                /*foreach ($cartDecode as $key => $cartItem)
                {
                    // IF THE TITLE MATCHES THE SIGNAL STRING
                    if ($cartItem->{"id"} == $cartItemID)
                    {
                        // REMOVE THIS OBJECT
                        unset($cartDecode[$key]);
                    }

                }*///cannot understand what you are trying to achieve here, but seems not wokring

                //$_SESSION['cart']['totalItems']--; // Deduct by 1. //again use this if you want 1st approach

                //use the following if you want the 2nd approach which i recommend
                $_SESSION['cart']['totalItems']-=$_SESSION['cart']['cartItems'][$product_id]['quantity'];
                unset($_SESSION['cart']['cartItems'][$product_id]); //this lines is working
            }
            else
            {
                $_SESSION['cart']['cartItems'] = $cartProduct;//what this line do, it seems a bit strange, not to say wrong...
            }
        }
    }

    $_SESSION['cart']['totalPrice'] = array_sum(array_map(function($item) {
        return $item['price'] * $item['quantity']; //it's quantity not totla_items
    }, //this calculation has to be outside of the else if ($_REQUEST['action'] == 'removeRow') in order to make the toal sum calculation in every pass
    $_SESSION['cart']['cartItems']));
    $cart = json_encode($_SESSION['cart']);
    echo ($cart);

以下是我用来检查代码的测试数据。

$_REQUEST['action'] = "addToCart";
//unset( $_SESSION['cart']);
/*$product_id = 7;
$product_name = "Bedrukt jurkje van chiffon";
$product_price = 20.5;
$product_size = "M";
$product_quantity = 1;
$total_product_price = 20.5;
*/
$product_id = 5;
$product_name = "Bedrukte Zomerjurk";
$product_price = 30.5;
$product_size = "M";
$product_quantity = 1;
$total_product_price = 30.5;

每次我运行脚本我评论/取消评论和产品时,将$ _REQUEST ['action']更改为removeRow以检查删除功能。