note 69627 modified in function.array-unique by danbrown
| From: | danbrown@php.net | Date: | Thu, 06 Nov 2008 15:02:44 +0000 |
| Subject: | note 69627 modified in function.array-unique by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-146223@lists.php.net to get a copy of this message | ||
This function below will remove multiple values from array, remove 'empty' fields an also
count how many times the given value occured.
it's rather slow and not 'elegant' but works.
usage:
<?php
$myarray = my_array_unique($myarray);
?>
in return it produces an 3 fields array:
1st is index number, 2nd is the value, 3rd is counter.
<?php
function my_array_unique($tablica)
{
$tnum=count($tablica);
$i=1;
$k=1;
$t[1]['product']="";
$t[1]['count']=1;
while($i<=$tnum) {
if (!array_multi_search($tablica[$i], $t)) {
$t[$k]['product']=$tablica[$i];
$t[$k]['count']=1;
$k++;
}
else {
$y=1;
while ($y<=count($t)) {
if ($t[$y]['product']==$tablica[$i])
$t[$y]['count']++;
$y++;
}
}
$i++;
}
$tablica=$t;
return $tablica;
}
?>
the function uses another function that i've found on the php.net site (i'm posting it
only for informational reasons - i can't remember who wrote it):
<?php
function array_multi_search( $p_needle, $p_haystack )
{
if( !is_array( $p_haystack ) )
{
return false;
}
if( in_array( $p_needle, $p_haystack ) )
{
return true;
}
foreach( $p_haystack as $row )
{
if( array_multi_search( $p_needle, $row ) )
{
return true;
}
}
return false;
}
?>
[EDIT BY danbrown AT php DOT net: The array_multi_search() function was originally written by
'czeslaw' and posted to the in_array() function manual entry on 18 February, 2006.]
--was--
This function below will remove multiple values from array, remove 'empty' fields an also
count how many times the given value occured.
it's rather slow and not 'elegant' but works.
usage:
$myarray=my_array_unique($myarray)
in return it produces an 3 fields array:
1st is index number, 2nd is the value, 3rd is counter.
function my_array_unique($tablica)
{
$tnum=count($tablica);
$i=1;
$k=1;
$t[1]['product']="";
$t[1]['count']=1;
while($i<=$tnum) {
if (!array_multi_search($tablica[$i], $t)) {
$t[$k]['product']=$tablica[$i];
$t[$k]['count']=1;
$k++;
}
else {
$y=1;
while ($y<=count($t)) {
if ($t[$y]['product']==$tablica[$i])
$t[$y]['count']++;
$y++;
}
}
$i++;
}
$tablica=$t;
return $tablica;
};
the function uses another function that i've found on the php.net site (i'm posting it
only for informational reasons - i can't remember who wrote it):
function array_multi_search( $p_needle, $p_haystack )
{
if( !is_array( $p_haystack ) )
{
return false;
}
if( in_array( $p_needle, $p_haystack ) )
{
return true;
}
foreach( $p_haystack as $row )
{
if( array_multi_search( $p_needle, $row ) )
{
return true;
}
}
return false;
}
http://php.net/manual/en/function.array-unique.php