Page 1 of 1

looking for a Function processing a 2-dim array.

Posted: Tue Jan 20, 2009 9:38 am
by indianyogi
I have a 2-dimensional array .. with following sample data:

#1 abc@gmail.com
#2 avneek@hotmail.com
#3 suresh@uk2.net
#4 suresh@uk2.net
#5 abc@gmail.com


where first column depicts serial number and second depicts email addresses.

Is there any function available in PHP which can help me process this array and produce a result much like Group-by/count function in SQL. something like :

2 abc@gmail.com
1 avneek@hotmail.com
2 suresh@uk2.net


Where first column depicts number of repetitions of every unique email address.

I hope i have framed my question clear enough.

Re: looking for a Function processing a 2-dim array.

Posted: Tue Jan 20, 2009 9:42 am
by Burrito
There is not a php function to return the number of any instance of a key=>value pair in an array.

shouldn't be too hard to write one though.

Re: looking for a Function processing a 2-dim array.

Posted: Tue Jan 20, 2009 2:17 pm
by jOE :D
Here you go, hope this helps!

Code: Select all

 
<?php
 
$myarray["#1"] = "abc@gmail.com";
$myarray["#2"] = "avneek@hotmail.com";
$myarray["#3"] = "suresh@uk2.net";
$myarray["#4"] = "suresh@uk2.net";
$myarray["#5"] = "abc@gmail.com";
 
function countEmails($array)
{
    foreach($array as $key => $value){
        $newarray[$value]++;
    }
    
    foreach($newarray as $key => $value){
        echo $value , ' ' , $key , '<br />';
    }
}
 
countEmails($myarray);
?>
 

Re: looking for a Function processing a 2-dim array.

Posted: Wed Jan 21, 2009 10:12 am
by indianyogi
<?php
function ArrayGroupByCount($_array, $sort = false) {
$count_array = array();

foreach (array_unique($_array) as $value) {
$count = 0;

foreach ($_array as $element) {
if ($element == $value)
$count++;
}

$count_array[$value] = $count;
}

if ( $sort == 'desc' )
arsort($count_array);
elseif ( $sort == 'asc' )
asort($count_array);

return $count_array;
}
?>