Forum Moderators: coopster
It does this:
It's a simple routine.
And I had it working pretty good but now I see there is a problem with the counting.
If the keyphrase is just one word, it's getting duplicated.
I'm not exactly sure where the problem is but I'll post the code and hopefully someone would be kind enough to point me to the right path to take.
here's the code:
#=========================================================
<?php
// define the test array
$ar1 = array ('three two one','one one','one','TWO','two','two','three','three');
echo'<hr><b>"ar1" - the original INPUT array</b><br>';
print_r($ar1);// convert all to lowercase
$ar2 = array();
foreach ($ar1 as $val) { $ar2[] = strtolower($val); }
echo'<hr><b>"ar2" - converted to lowercase. Sending this to function "count_items" below.</b><br>';
print_r($ar2);
// count
$counted = array();
$counted = count_items($ar2);
echo'<hr><b>"counted" - array sent back from function "count_items"</b><br>';
print_r($counted);
// function to count and sort
function count_items($ar2) {
$final_ar = array();
foreach ($ar2 as $needle) {
$needle = strtolower($needle); // convert to lower
if ( in_array($needle, $final_ar) ) {
#echo $needle.' is in array<br>';
} else {
$final_ar[] = $needle;
}
}
// now count them up
// define some vars
$count_array = array();
$sortme = array();
$haystackArray = $ar2;
$count = "";
foreach ($final_ar as $v) {
$needle = $v;
$count = substr_count ( implode( $haystackArray ), $needle );
$count_array[] = $count;
$sortme[] = $count.'Š'.$v;
}
rsort($sortme,SORT_NUMERIC);
return $sortme;
} // end of function
?>
What this outputs is this:
#=========================================================
[b]"ar1" - the original INPUT array[/b]
Array
(
[0] => three two one
[1] => one one
[2] => one
[3] => TWO
[4] => two
[5] => two
[6] => three
[7] => three
)
[b]"ar2" - converted to lowercase. Sending this to function "count_items" below.[/b]
Array
(
[0] => three two one
[1] => one one
[2] => one
[3] => two
[4] => two
[5] => two
[6] => three
[7] => three
)
[b]"counted" - array sent back from function "count_items"[/b]
Array
(
[0] => 4Štwo
[1] => 4Šone
[2] => 3Šthree
[3] => 1Šone one
[4] => 1Šthree two one
)
#========================================================= So as you can see. The item capital "TWO" is also being counted as existing inside of "one two three".
And "one" is counted also inside of "one one".
How can I make it so each item is unique and it will not double the counts like that?
Any help is appreciated.
Thanks.
-Jeff
That should return:
Array
(
[three two one] => 1
[one one] => 1
[one ] => 1
[two] => 3
[three ] => 2
)
Then if you need the format you had you can just loop through the results:
foreach($counted as $key => $val){
$counted2[] = $val."¦".$key;
}