Jump to content

Count words in array, sort and filter by variable occurences


Anti-Moronic

Recommended Posts

Say I have this array:

 

array(
0 => time
1 => time
2 => to
3 => to
4 => to
5 => fly
);

 

and 2 variables - $occMin and $occMax as number of occurrences.

 

If:

 

$occMin = 2;
$occMax = 3;

 

I want to produce sorted list with most occurrences at the top:

 

array(
0 => array('to', 3),
1 => array('time', 2)
);

 

My face just melted at the thought of even beginning to tackle this. Is this somewhat possible? would it require a monster function or am I missing some native php functions which could lend a hand?

there is probably a much better way to do this but I program very simply, 'cos I have to debug it later !!

<?php
// test.php
$arr = array(
0 => 'time',
1 => 'time',
2 => 'to',
3 => 'to',
4 => 'to',
5 => 'fly'
);

$res = array();
foreach($arr as $val) {
if (count($res) == 0) {
	$res[$val] = 1;
} else {
	foreach($res as $key1=>$val1) {
		if ($val == $key1) {
			$res[$key1] = ($val1+1);
			break;
		}
		$res[$val] = 1;
	}
}
}
arsort($res);
foreach($res as $key=>$val) {
echo "<BR>".$key." appears ".$val." times";
}
die("<br>finished");
?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.