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.
looking for a Function processing a 2-dim array.
Moderator: General Moderators
-
indianyogi
- Forum Newbie
- Posts: 7
- Joined: Tue Jan 20, 2009 9:16 am
Re: looking for a Function processing a 2-dim array.
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.
shouldn't be too hard to write one though.
Re: looking for a Function processing a 2-dim array.
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.
<?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;
}
?>
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;
}
?>