Page 1 of 1

Trying to count occurences of uknown array elements

Posted: Thu Jun 24, 2004 9:17 am
by primate
Hi

I'm writing a scrip to crunch through the Syslogs stored in an MS SQL database from various PIX's in my organisation.

For a particular part of the script I have retrieved all the data I need (FWIW source IP's of connection attempts), formatted and stripped extraneous stuff and got them sitting in an indexed array. Now I'm stuck.

What I am trying to do is run through the array and at each occurence of a new IP address do something with it (I won't know what the IP addresses are at this stage) which will let me count the number of times each IP address is found, then order the output by the most frequently occuring IP address. hmm....

I'm really stuck, new to php in general and this is my first attempt at doing something useful with it so any help appreciated.

Posted: Thu Jun 24, 2004 9:24 am
by Grim...
[php_man]array_count_values[/php_man]() should solve all your problems.

Posted: Thu Jun 24, 2004 9:25 am
by primate
duh, I'd read that earlier but completely missed the point of it :oops:

Thanks, I'll try it out now!

Posted: Thu Jun 24, 2004 9:25 am
by Wayne
maybe try

Code: Select all

$array_count = array_count_values($your_array); // your array, is the array containing all the ip's
sort($array_count);
reset($array_count);

Posted: Thu Jun 24, 2004 9:30 am
by Grim...
I think array_count_values sorts itself, highest first.

Code: Select all

<?php

//assuming the IP array is called '$ip';

print_r(array_count_values($ip)); 

?>
Should do the trick.

Posted: Thu Jun 24, 2004 10:17 am
by primate
I ended up using:

Code: Select all

<?php

$sortedips = array_count_values($sourceips);
natsort($sortedips);
$rsortedips = array_reverse ($sortedips);
reset ($sortedips);

?>
array_count_values() made the key the IP address with the element the number of connection attempts.

I used natsort() to sort by the elements then array_reverse () 'd it so the highest no. of connection attempts was at the top.

Is there a better way?