View Full Version : Grouping Arrays?

Lee Stevens
11-30-2006, 03:02 AM
I'm not sure if you can do this.

I'm making a shoping cart, which uses Session, but for every quantity it takes the id number and adds it by one, so if i had product ID 1, but i wanted 10 quanty, it would show when i print it "1,1,1,1,1,1,1,1,1,1", is there anyway, when i use count($_SESSION['name']); it only counts one of the 1's? Same as if i had 10 2's or 10 3's?

Let me no if you get what i mean hehe, thanks for the help.

11-30-2006, 03:48 AM
So, even if you have ten '2's, you don't want it to report "10" you want it to report "1"?

11-30-2006, 04:46 AM
Post your code.

Lee Stevens
11-30-2006, 05:37 AM
Yes Tyree, that is correct ;)

11-30-2006, 08:49 AM
I'd recommend array_count_values() (http://www.php.net/array_count_values)
or array_unique() (http://www.php.net/array_unique)

Lee Stevens
11-30-2006, 03:37 PM
I have used them both i get a error.

Al i need to do is count all the ones as one, and all twos as a two, etc etc.

11-30-2006, 04:14 PM
If you did an array_count_values() on your array, couldn't you then just extract the keys that resulted to tell you the item IDs?

$array = array(1,1,1,1,2,2,2,3,3,3,3);

if (is_array($array)){

$sepValues = array_count_values($array);

print "<br />";
foreach ($sepValues AS $key=>$value)
print "Item: ".$key." Quantity: ".$value."&nbsp;&nbsp;&nbsp;";


Output would be:
Array ( [1] => 4 [2] => 3 [3] => 4 )
Item: 1 Quantity: 4 Item: 2 Quantity: 3 Item: 3 Quantity: 4