Jump to content

Passing multidimensional Array's


7blake

Recommended Posts

I recently posted a simple query about ISSET and finally got that simple problem solved thanks to you guys. But I've hit a new snag. I've create a simple sort of cart, or record counter. While I can add/remove/clear items and display their affilated arrays, I don't know how to cycle through a multidimensional array that is dynamically set.

 

Something like $_SESSION['Primary'][$items][$attributes] - Where $items is a dynamic set, and $attributes is a fixed set of keys with values.

 

I can target individual $Items, or display all the items in there. But I can't display all the Items and their subsequent $attributes aswell. Do I have to write 1 set of Ajax code for just displaying the $items, and another for each individual set of $attributes? Or is their a way to cycle through each $item, and then all of it's(or specific) $attributes and values? I've tried using loops which logically work, but I can't pass it through json_encode.

 

Is there any documentation I could read in relation to this? I feel this is the key component to manuvering through a database of sorts. I'm just not entirely sure how to go about accessing multidimensional Array's without a ton of code that becomes redudent. And even then, it wouldnt work well with a dynamic setup.

Edited by 7blake
Link to comment
Share on other sites

Do I take it that you have something like

$_SESSION['Primary'] = array (
            'item1' => array (
                            'color' => 'red',
                            'size'  => 'large',
                            'price' => 25.00,
                            'qty'   => 2
                        ),
            'item2' => array (
                            'color' => 'orange',
                            'size'  => 'small',
                            'price' => 15.00,
                            'qty'   => 1
                        ),
            'item3' => array (
                            'color' => 'blue',
                            'size'  => 'medium',
                            'price' => 65.00,
                            'qty'   => 1
                        )

        );

If so then to loop through the attributes of "item2" it would be

foreach ($_SESSION['Primary']['item2'] as $attr => $value) {
    echo "$attr : $value<br>";
}

giving

color : orange
size : small
price : 15
qty : 1
  • Like 1
Link to comment
Share on other sites

Ah you got me thinking :P

 

I've been trying to do this with json_encode.. when infact I can just do it with basic ajax/php data transfer. (Sorry, I don't know the correct way of saying this).

 

Here's my code.

<!DOCTYPE HTML >
<html>
<head>

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script type='text/javascript'>


    $(document).ready(function() {
    		    
    		    $("#updateCart").click(function() {    // Update view on cart
    		    		    
    		    		    $("#cartStatus").fadeOut(function() {
    		    		    		    $(this).empty();
    		    		    
    		     $.get(
			'info.php',
			{"cartDisplay2" : "test"},
                function(data) {
			$('#cartStatus').append(data);
		
    		    });
    		    		    }).fadeIn();
    		    });
    		        		    
    		   var name; 
    		   
    		    	
    		    	$(".item").click(function() {     // select Item 
    		    		name = $(this).attr("id");
    		    		$(".item").css({"border" : "1px solid black", "color" : "black"});
    		    		if (this.id== name){ 
    		    		
    		    		$(this).animate({width:"0px", height:"0px", top:"+=25px", left:"+=25px"}, 200, function() {
    		    				$(this).css({"border" : "1px solid blue", "color" : "blue"});
    		    		}).animate({width:"50px", height:"50px", top:"-=25px", left:"-=25px"}, 200);
    		    		}
    		    	});
    		      		    	
        $("#button").click(function() { // Add to Cart
        		
        		$("#click").fadeOut(300, function() {
        		$(this).empty();
        	
            $.get(
                "info.php",
                {"name":name},
                function(data) {
                    $.each(data, function(k,v){
                    		    
                        $("#click").append(k + " : " + v + "<br />").fadeIn();
                    })
                    $("#click").append("--------------------\n");
                },
                "json"
            )
        						});
            
        });
        
        $("#minus").click(function() { // Minus From cart
        		
        		$("#click").fadeOut(300, function() {
        		$(this).empty();
        		
            $.get(
                "info.php",
                {"name1":name},
                function(data) {
                    $.each(data, function(k,v){
                    		    
                        $("#click").append(k + " : " + v + "<br />").fadeIn();
                    })
                    $("#click").append("--------------------\n");
                },
                "json"
            )
        						});
            
        });
        
           $("#clear").click(function() { // Clear from Cart
        		
        		$("#click").fadeOut(300, function() {
        		$(this).empty();
        		
            $.get(
                "info.php",
                {"clear":name},
                function(data) {
                    $.each(data, function(k,v){
                    		    
                        $("#click").append(k + " : " + v + "<br />").fadeIn();
                    })
                    $("#click").append("--------------------\n");
                },
                "json"
            )
        						});
            
        });
    })
</script>

<style>
#container {
	position:absolute;
	width:10%;
	height:15%;
	top:5%;
	border:1px solid black;
	overflow:auto;
}

#cartStatus {
	position:absolute;
	width:12%;
	height:20%;
	top:5%;
	left:11%;
	border:1px solid black;
}

.item {
	width:50px;
	height:50px;
	position:absolute;
	border:1px solid black;
	font-size:.75em;
	text-align:center;
	top:266px;
}
#item1 {
	left:10px;
}

#item2 {
	left:64px
}

#item3 {
	left:118px
}


</style>

</head>
<body>
<input type="button" name="button" id="button" value="Add">  
<input type="button" name="minus" id="minus" value="Minus">
<input type="button" name="clear" id="clear" value="Clear">
<input type="button" name="clear" id="updateCart" value="updateCart">

<div id="container">
	<div id="click"></div>
</div>
<div id="cartStatus">
</div>


<div id="item1" class="item">Item 1</div>
<div id="item2" class="item">Item 2</div>
<div id="item3" class="item">Item 3</div>
</body>
</html>
<?php

session_start();

// Add to Cart

if (isset($_GET['name'])) {
    $itemId = $_GET['name'];
        
    if (isset($_SESSION['cart'][$itemId])) {
    	    $totalPrice = 2.5;
        $_SESSION['cart'][$itemId]['Quantity']++;
          $quantity = $_SESSION['cart'][$itemId]['Quantity'];
          $price = $_SESSION['cart'][$itemId]['Price'];
          $totalPrice = $quantity * $price;
          $_SESSION['cart'][$itemId]['TotalPrice'] = $totalPrice;
    }
    else {
    	$totalPrice = 2.5;
        $_SESSION['cart'][$itemId] = array('Id' => $itemId, 'Quantity'=>1, 'Price'=>2.50, 'TotalPrice' => $totalPrice);
    $quantity = $_SESSION['cart'][$itemId]['Quantity'];
    $price = $_SESSION['cart'][$itemId]['Price'];
    $totalPrice = $quantity * $price;
    $_SESSION['cart'][$itemId]['TotalPrice'] = $totalPrice;
    }
    

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

}
else echo '';


// Minus from Cart

if (isset($_GET['name1'])) {
    $itemId1 = $_GET['name1'];
    
    if (isset($_SESSION['cart'][$itemId1])) {
        $_SESSION['cart'][$itemId1]['Quantity']--;
        $quantity = $_SESSION['cart'][$itemId1]['Quantity'];
          $price = $_SESSION['cart'][$itemId1]['Price'];
          $totalPrice = $quantity * $price;
          $_SESSION['cart'][$itemId1]['TotalPrice'] = $totalPrice;
    }
    else {
    	    $totalPrice = 2.5;
        $_SESSION['cart'][$itemId1] = array('Id' => $itemId1, 'Quantity'=>1, 'Price'=>2.50, 'Total Price' => $totalPrice);
	    $quantity = $_SESSION['cart'][$itemId1]['Quantity'];
	    $price = $_SESSION['cart'][$itemId1]['Price'];
	    $totalPrice = $quantity * $price;
    }
    

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

}
else echo '';
     

// Clear from Cart
if (isset($_GET['clear'])) {
    $itemClear = $_GET['clear'];
    
    if (isset($_SESSION['cart'][$itemClear])) {
        $_SESSION['cart'][$itemClear]['Quantity'] = 0;
        $quantity = $_SESSION['cart'][$itemClear]['Quantity'];
          $price = $_SESSION['cart'][$itemClear]['Price'];
          $totalPrice = $quantity * $price;
          $_SESSION['cart'][$itemClear]['TotalPrice'] = $totalPrice;
    }
    else {
    	   echo '';
    }
    

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

}
else echo '';
                    
// Display Cart Contents


if(isset($_GET['cartDisplay'])) {

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

if(isset($_GET['cartDisplay2'])) {


	foreach ($_SESSION['cart'] as $item => $value){
		
		
		
		foreach($_SESSION['cart'][$item] as $test){
			
			echo $test . " : ";
		}
		
		
	}
	
	
}

?>                                                       

(it's just a practice one. There's lots of things not coded in. Nothing is unset, or disabling -1 counters, or the cart display when there are no contents. But it works fine for now I think. Unless you can see I'm going about something very wrong to the standards today)

So this sorta works fine. I can just design the PHP itself to be better displayed. So is one of json's methods for passing entire arrays through ajax?
 

Edited by 7blake
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.