looking for a Function processing a 2-dim array.

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
indianyogi
Forum Newbie
Posts: 7
Joined: Tue Jan 20, 2009 9:16 am

looking for a Function processing a 2-dim array.

Post 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.
User avatar
Burrito
Spockulator
Posts: 4715
Joined: Wed Feb 04, 2004 8:15 pm
Location: Eden, Utah

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

Post 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.
jOE :D
Forum Newbie
Posts: 2
Joined: Wed Jan 14, 2009 4:50 pm

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

Post 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);
?>
 
indianyogi
Forum Newbie
Posts: 7
Joined: Tue Jan 20, 2009 9:16 am

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

Post 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;
}
?>
Post Reply