2017-11-07 26 views
4

まずは他のオプション、質問と回答をチェックしましたが、悲しいことにそれらは私にとってはうまくいきませんでした。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:1、製品のJSONの結果:

だから、現在、私のコードは基づいています。最後の数日間の進捗状況を結合するので、更新

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

UPDATE

私はアクションメソッドが好きで、@FranciscoRodríguezの答えは彼が計数方法について私にアドバイスして以来ほとんど役に立たなかったので、@devionNLの答えには、(仕事しなかった)

@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の合計価格を得ることに苦労しています。

{"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で完全なカートは次のようになります:以下のよう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.どのように1行を削除することができますか(ID == "", Then delete) 2.カートの全額をどのように計算できますか? 3.ダバターゼの中に注文するには、どのように各行を選択することができますか? (ID、名前など)。私はforeach()声明を使う方法を考えていましたか?

ご不明な点がございましたら、コメントにお尋ねください。

いつもありがとうございます!一見

+0

'$ total_items ['total_items']'の値は何ですか?それが有効な値を持っている場合は、ループを使用してarray_push()を実行してください。 –

+0

@ RedBottle JSONファイルのtotal_itemsの値は0に設定されています。配列のプッシュをセッション数に設定します。はい、カウントが機能しているかどうかを確認しました。 – Deathstorm

+0

jsonは文字列なので、$ _SESSION ['cart'] ['cartItems'] [$ product_id] 'または' $ _SESSION ['cart'] ["cartItems"] 'にjson文字列を正確に入れていますか?または、カート全体がjsonとして保管されていますか? – jeroen

答えて

1
:最後に、あなたは、単にこれです、私はあなたがやろうとしていると思う何

(また、製品のキーではないです)キー'cartItems'で、JSONオブジェクトにその全体の配列を追加しよう

ベストプラクティスは、お客様の製品情報をデータベースに保存し、クライアントが真実を伝えていることを最初に確認できないため、クライアントがすべての情報をサーバーに送信しないようにすることです。

基本的には、追加/削除と追加したいproductIdだけですので、価格でオブジェクトを返すことはできますが、クライアントはその価格を '更新'できません。

$ 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']); 
+0

マイナーなことに、json_encodeはcartItemsだけでなく、$ _SESSION ['cart']を返す必要があります。そうしないと、totalPriceのようなサイドプロパティは無視されます。 – DevionNL

+0

私は現在、 '$ .REQUEST ['action'] ==" name ")'セクションを使用していますが、現在 '$ .ajax'というポストリクエストを使用しています。 'if statements'? – Deathstorm

+0

$ _REQUESTは$ _POSTと$ _GETを組み合わせたものです。 .ajaxを使ってURLに?action = addを追加すると、$ _REQUESTはそれを持ち、$ _GETはそれを持ちます。 – DevionNL

2

私はいくつかの奇妙なものがここで起こって見ることができます:

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

あなたは1つの製品の$arr JSONオブジェクトに格納しています。その後、総数(実際にはカートのルート配列のサイズを数えています)を数えた後、配列'total_items'に配列を格納しようとします。

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

はい、あなたが言っているように: "やろうとしています"。しかし、それは動作しません。私の方法かあなたの答えは悲しいことに私が探している結果を与えていません – Deathstorm

+0

あなたの答えから私が得意とする応答はNULLです – Deathstorm

+0

@Deathstormだからこそ私はエコーも印刷もしていません。 '$ _SESSION ['cart'] ['cartSize']' '$ _SESSION ['cart'] ['cartItems']'のサイズです。 – FcoRodr

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); 

を。 「cartProduct」のキーとして「cartItemID」を使用します。アイテム数と合計価格の "カート"配列に2つのキーがあります。そして、あなたの質問に答えるために:

  • つもりが、「$ _SESSION [ 『カート』] [」totalprice「]」あなたは、単にできるデータベースに挿入する

  • にあるカートの合計金額を$ _SESSION ['cart'] ["cartItems"]配列をforeachします。

+0

あなたのアイデアは好きですが、すでに@devionNLの例で作業しています。あなたの答えからのデータベースの挿入が何かであることを心に留めているので、私はこの答えをアップ・ヴォーヴングしています – Deathstorm

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; 

私は/アンコメントし、製品をコメントスクリプトを実行するたびに、削除機能をチェックするためにremoveRowする$ _REQUEST [「行動」]を変更します。

関連する問題