Forum Moderators: coopster

Message Too Old, No Replies

Combining arrays with quantities

         

Nutter

9:14 pm on Jun 19, 2007 (gmt 0)

10+ Year Member



I've been working on this for the past couple of days and every thing I've tried has some sort of problem that frustrates me to a point I've been starting over.

What I have is an array of items and each item has a quantity of 1.

For example...

$item['description']='Whatever';
$item['quantity']='1';
$item['id']='1';
$item['id2']='1';

$item['description']='Whatever';
$item['quantity']='1';
$item['id']='1';
$item['id2']='1';

$item['description']='Something else';
$item['quantity']='1';
$item['id']='2';
$item['id2']='2';

What I need to do is create an array out of this that combines the members with the same description, id, and id2 and with the quantity totaling the quantity of all the members that match.

Any suggestions as to where to start? I don't doubt that it can be done, but I've been staring at the code so long that I'm starting to go cross-eyed.

[edited by: Nutter at 9:14 pm (utc) on June 19, 2007]

jatar_k

12:26 pm on Jun 20, 2007 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



how is the array being constructed? is it coming from a database?

Nutter

1:40 pm on Jun 20, 2007 (gmt 0)

10+ Year Member



It's a shopping cart script, but I kept each quantity at 1 in the database because it's possible to purchase packages of items and I needed a way to slide an individual item into a package and storing quantities together seemed to complicate that. I'm grouping on 3 different array members - sort of like all Large, Blue, Style 33 shirts need to be together, but an X-Large, Blue, Style 33 shirt shouldn't be part of the grouping.

As is normal for me though, as soon as I posted here I had an idea that worked very well. It's happened probably 10 or 15 times that I've struggled with a task, posted here, and then within a few minutes had a brainstorm that fixed the problem. :)

What I'm doing is looping through the array and checking for a key in the output array of [size:color:style]. If it exists just add one to [size:color:style][quantity]. If it doesn't exist then add it. It's about 20 lines of code that works doing what I couldn't get to work in in several hundred lines.

jatar_k

1:42 pm on Jun 20, 2007 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



isn't that always the way

and that would be what I would have suggested

nice work