Link to home
Start Free TrialLog in
Avatar of Crazy Horse
Crazy HorseFlag for South Africa

asked on

How to json encode two arrays

I have set up a basic shopping cart which loops through the item id's in the cart and retrieves product details from the database from the id's. I am putting the data into an array and json encoding it. Their shopping cart contents are then displayed to them via jQuery.

I want to also show them the subtotal but I cannot put that into the loop. When putting it outside of the loop I don't know how to json encode it.

I tried this:

echo json_encode(array($cart_details, $response));

Open in new window


But even if that is correct, I don't know how to extract the arrays in jQuery.

$itemsInCart = "";
$response = array();

if(!isset($_SESSION['cart_array'])) {
	
	$itemsInCart = 0;

} else {

		$featured = "Yes";
		$cartTotal = "";
		foreach($_SESSION['cart_array'] as $each_item) {
			$item_id = $each_item['item_id'];
			
			$stmt = $link->prepare("SELECT `product_name`, `price`, `pic_name` FROM `products` as `p` INNER JOIN `product_images` as `pi` ON p.`id` = pi.`product_id` WHERE p.`id` = ? AND `featured` = ?");
			$stmt->bind_param("is", $item_id, $featured);
			$stmt->execute();
			$result = $stmt->get_result();
			$numRows = $result->num_rows;
			if($numRows > 0) {
				while($row = $result->fetch_assoc()) {
					$product_name = sanitize($row['product_name']);
					$price = sanitize(money_format('%.2n', $row['price']));
					$subtotal = money_format('%.2n', $each_item['quantity'] * $price);
					$pic_name = $row['pic_name'];
					$cartTotal = $subtotal + $cartTotal;
					$quantity = $each_item['quantity'];
					
					$cart_details[] = array(
					
					"product_name" => $product_name,
					"price" => $price,
					"subtotal" => $subtotal,
					"pic_name" => $pic_name,
					"each_item" => $quantity,
					"subtotal" => $subtotal,
					
					
					);

				}
			}
			
			$stmt->close();
		}
	
	$response['total'] = $cartTotal;
	
	echo json_encode(array($cart_details, $response));
}

Open in new window



$.ajax({
		url: 'functions/show-cart.php',
		type: 'POST',
		dataType: 'json',
		})
		
		.done(function(data) {
			$.each(data, function(index, item) {
				
				var showCart = `

				<div class="row hr marg-b-30 marg-t-30">
						<div class="col-md-2 col-sm-2 col-xs-12 marg-b-30">
							<img src="uploads/${item.pic_name}" alt="${item.product_name}" class="">
						</div>
						<div class="col-md-5 col-sm-5 col-xs-12 marg-b-30">
							<a href="#" class=""><b>Product</b></a><b class="right">${item.price}</b>
							<p class="">${item.product_name}</p>
							<button class="btn btn-xs bg-color--second removeItem" data-id="{$item_id}" data-itr="{$i}">Remove <i class="material-icons">delete</i></button>
							
						</div>
						<div class="col-md-3 col-sm-3 col-xs-12 marg-b-30">
							<div class="input input-counter">
								<div class="input__helper pos-left pointer input-counter__plus cartPlus" data-itr="{$i}">
									<i class="material-icons ico-xs"></i>
								</div>
								<input type="text" class="text-center" readonly="" value="${item.each_item}">
								<div class="input__helper pointer input-counter__minus">
									<i class="material-icons ico-xs"></i>
								</div>
							</div>
						</div>
						<div class="col-md-2 col-sm-2 col-xs-12 marg-b-30 text-right text-left-xs">
							<span class="price-xs">R${item.subtotal}</span>
						</div>
					</div>`;
				
					$( ".somediv" ).append(showCart);
				
			});
		})
	
	.fail(function (jqXHR, textStatus, errorThrown) {
				console.log(textStatus + ': ' + errorThrown);
				console.warn(jqXHR.responseText);
			});

Open in new window

Avatar of HainKurt
HainKurt
Flag of Canada image

1. put that one outside
2. dont put anything

post the result str for both...

with jS we can get the total or loop and calculate total somehow...
but we need to see a sample first
Avatar of Crazy Horse

ASKER

@HainKurt,

Sorry, I don't understand what you mean by 1. put that one outside 2. don't put anything

?
we need sample string with and/or without total in the result...
and based on that, we can get total in both case...

or what is the current result now? and what do you want to get from current result?
we can loop in js and get that sum after ajax call
ASKER CERTIFIED SOLUTION
Avatar of Julian Hansen
Julian Hansen
Flag of South Africa image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Just for interests sake you could have accessed the items from your original code like this
.done(function(resp) {
  //    resp[0]  => array of cart items
  //    resp[1] => the total
});

Open in new window

But using an object or named (assoc) indices is better.
Thanks, Julian. That is easier than I thought!

But I am just having a little trouble and have one question. Firstly, how come I now don't need the $.each anymore? If I console.log out data.cart it shows me the results of the php loop i.e.: multiple products in the cart even without using $.each. Like this:

.done(function(data) {
	console.log(data.cart);
		console.log(data.total);

Open in new window


Secondly, using $.each I was getting individual items from the array like item.product_name

I can't seem to get that using your method, just because I don't know how. I tried data.cart.product_name but that returned 'undefined'.
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Brilliant, thanks!
You are welcome.