I would like to create a function, that adds up the values (the numbers) of each array, if the first value already exists in the array (the letters), so that above posted array, would become:
I've tried to first get the letters in a new array, and make sure that's unique, and then go through $test again, to, if a letter matches, add the values up...but well, that doesnt really seem to work.
This might be a case of needing to understand the context, and perhaps finding a very different solution. For instance, if this array you're dealing with is the result of a database query, my suspicion is that it could be handled more easily and efficiently at the database level, such as with a GROUP BY query with SUM() functions for each of those numeric fields.
"Please give us a simple answer, so that we don't have to think, because if we think, we might find answers that don't fit the way we want the world to be."
~ Terry Pratchett in Nation
You solution wouldnt work for me though, it gets the sum of the array, where i would like to add up values. The array (key?) holds an article number, the numbers are quantities of variations of article; if an article number is being inserted in the array twice, i would like to add up the quantities, perhaps something looking like:
As it is now, the php just echoes what it sees, so it would list "cube" twice, with its quantities, where i would like to have it listed just once, with the quantities added up, so that the array would look like:
The array is not a result of a database query. I get the data from a form, which saves the data in a (temp) array, which gets pushed into the array i want to sort ($test in this case)
"Please give us a simple answer, so that we don't have to think, because if we think, we might find answers that don't fit the way we want the world to be."
~ Terry Pratchett in Nation
The script NogDog posted works well for me, however i run into the problem of how to echo the key and the values.
I would like to echo out the key (the product id) and the values (quantities of different variations of that product), something like:
Product: a, Red: 2, Blue, 3, Yellow, 4
I've been trying with key(), but that only returns 0 ?? I've been trying quite a few things, obviously also googled it and searched on the forums here, but i cant seem to find the answer i'm looking for. I either get no result, 0 or 'Array' when i echo.
Would appreciate it a lot if anyone could help me with some directions!
"Please give us a simple answer, so that we don't have to think, because if we think, we might find answers that don't fit the way we want the world to be."
~ Terry Pratchett in Nation
Fortunately, im almost done with the page im working on. A very heavy delivery as i'm pretty new to php and i'm trying to learn as i go (i have a different scripting background, but eager to learn PHP as well)
Now all i need to do is sort out this session issue, and i think im good to go.
Bookmarks