Jump to content

Adding to existing elements in an array


SharkBait

Recommended Posts

I am trying to count up how many instances something happens.

I have an query that pulls values from a table.  The values are Items and Qty.  What I'm trying to do is create an array of the Items and their total quantities.

[code]
<?php
$UNITS = array();

$UNITS[$result['Item']] .= $result['Qty'];

?>
[/code]

Now this just adds the number to the number that already exists in the array.

How do I add the values of waht is in the array to the new value and put it back into the array?

List is something like:

Widget1  - 14
Widget2  - 3
Widget2 - 5
Widget3 - 2
Widget1 - 6

So I would have:

20 Widget1s
8 Widget2s
2 Widget3
Link to comment
https://forums.phpfreaks.com/topic/22265-adding-to-existing-elements-in-an-array/
Share on other sites

I'd have to do a seperate query.

Right now my query is this:

[code]
SELECT * , COUNT(*) FROM RMAs GROUP BY RMANumber
[/code]

There can be multiple items for a single RMANumber. Can I somehow incorporate the SUM in to my SELECT?
Maybe I explained it wrong or I'm a bit confused.

an RMA entry might look like this

Line #    |    Unit      |RMANumber    | Notes
----------------------------------------------
1            | Widget1  | 9090999        | Blah
----------------------------------------------
2            | Widget2  | 9090999        | Mroe Blah
----------------------------------------------
3            | Widget1  | 9090999        | WOo Blah
----------------------------------------------

So in the RMA above it has 2x Widget1s and 1x Widget2s

My main query looks like this:

[code]
SELECT *, COUNT(*) FROM RMAs WHERE Received >= '{$MyDate}' AND Received != '0000-00-00 00:00:00' GROUP BY RMANumber
[/code]
Where MyDate is a user inputed date like 2006-06-01 00:00:01

Then I loop through the result to print out entries and group them by their RMANumbers and output them to the screen. At the same time I need a running total of how many Units of each time this loops sees.



ah, ok, i think i see... so, something like this might help:
[code]
<?php
$totals = array();
while ($x = mysql_fetch_array($sql)) {
  $item = $x['unit'];
  if (isset($totals[$item])) $totals[$item]++; // increment it since it's already set
  else $totals[$item] = 1; // otherwise, set it to one since it's the first one we've seen
}
?>
[/code]

does that help at all?

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.