Jump to content

to multi-dimention an array or not


Recommended Posts

So, I'm working with a shopping cart that uses a simple array to track the contents: array key is the database key for the product, the value is just the quantity of that item that's in the cart. Prices, etc, are stored in the database and can be called for pretty easily.

 

Here's the wrench. There are two items that have "options" - lets call it color. Of the thirty items available, two of them have an option to come in red, yellow, blue, black, or white. The rest don't have an option. So, would complicating this a bit with a multidimensional array make sense or is there a better way to do this?

 

I thought of doing a separate array that tied the option to the product - but if they wanted to order two yellow AND one red one, I'd be stuck - right?

Link to comment
https://forums.phpfreaks.com/topic/207306-to-multi-dimention-an-array-or-not/
Share on other sites

Just make it multi-dimensional, would be a lot easier to read as well. Example:

 

Array
(
    [0] => Array
        (
            [id] => 45
            [qty] => 3
            [options] => Array
                (
                )

        )

    [1] => Array
        (
            [id] => 47
            [qty] => 1
            [options] => Array
                (
                    [color] => red
                )

        )

    [2] => Array
        (
            [id] => 47
            [qty] => 3
            [options] => Array
                (
                    [color] => green
                )

        )

    [3] => Array
        (
            [id] => 61
            [qty] => 1
            [options] => Array
                (
                )

        )

)

 

It provides a much cleaner way of accessing the different elements. The only thing you'd need to do, is when adding products with the options, check to see if their is a product already existing with that option set.

Yeah, that's what I figured. I didn't array the options, but I went ahead and multidimensioned the array. They key is now just an incremental value. The values I'm storing are id, qty, and options.

 

It's amazing that adding just one little integer value took the code from five lines to fifty-five lines. The complexity comes from the loop and if statements to determine if the product is already in the cart - as you mentioned.

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.