Forum Moderators: coopster

Message Too Old, No Replies

Arrays and Grouping

         

playxchange

10:35 pm on Jul 25, 2008 (gmt 0)

10+ Year Member



First, hello there to everyone; just joined because I've been so many useful information here that this place became an awesome knowledge base :)

Secondly, to the issue!. Which is "pretty easy" for an average programmer -which I'm really not-.

The thing is the following. I've got an array on one script, which gives me some results:

1031105
1031105
1031109
1031109
1031113
1031113
1031113
1031115
1031115
1031119
1031119
1031120
1031120
1031121
1031121
1031121
1031406
1031406
1031406
1031619
1031619
1031923
1031923
1031923
1032415
1190304

etc.

This comes, like I've said, from the array $data['award']. I *cannot* modify the source of this information (which is based on a PHP class).

What I need basically is to group the same numbers, count the amount, and do something after that with each group.

For instance:

1031105
1031105
= 2 equal values

1031113
1031113
1031113
= 3 equal values

I don't if I'm being clear, but I hoped I did.
Any thoughts?.

Appreciated!

Sekka

11:26 pm on Jul 25, 2008 (gmt 0)

10+ Year Member



Welcome to Webmaster World! Hope this helps,

$formatted = array ();
foreach ($data['award'] as $award) {
if (!array_key_exists ($award, $formatted)) {
$formatted[$award] = 1;
} else {
$formatted[$award] ++;
}
}

This code creates an array ($formatted) with each award as the array key, and the number of times that key occurs as the value.

For example,

Array
(
[15026] => 3
[15027] => 1
[15028] => 1
[15029] => 2
)

nick279

11:32 pm on Jul 25, 2008 (gmt 0)

10+ Year Member



$values = array_count_values($data['award']);

Sekka

11:51 pm on Jul 25, 2008 (gmt 0)

10+ Year Member



How did I forget that?! Good call :P

nick279

11:58 pm on Jul 25, 2008 (gmt 0)

10+ Year Member



I always check the php manual first - 95/100 it's been done bigger & better

playxchange

7:46 pm on Jul 26, 2008 (gmt 0)

10+ Year Member



Will try something around that. So far, no success (like Borat would say).

I'm not at home, but I'll post the error I've got as soon as I get there.

$values = array_count_values($data['award']);
returns an error :-/

Thanks both of you, your help is extremely well appreciated, as well your speed to reply. Thank you guys, you are the meaning of an open source community.