<?php
function sortKeywords(array $phrases) {
if (empty($phrases)) {
return $phrases;
}
// group by word count
$byWordCount = array();
foreach ($phrases as $kw) {
$kw = preg_replace('/\b+/', " ", $kw);
$wordCount = count(explode(" ", $kw));
if (!array_key_exists($wordCount, $byWordCount)) {
$byWordCount[$wordCount] = array();
}
$byWordCount[$wordCount][] = $kw;
}
// within every group sort by average word length
$sortByWordLen = function ($a, $b) {
$getAverageWordLen = function (array $words) {
$totalLen = 0;
foreach ($words as $w) {
$totalLen += strlen($w);
}
return $totalLen / (count($words));
};
$wordsA = explode(" ", $a);
$wordsB = explode(" ", $b);
$averageLenA = $getAverageWordLen($wordsA);
$averageLenB = $getAverageWordLen($wordsB);
if ($averageLenA < $averageLenB) {
return 1;
} else if ($averageLenA > $averageLenB) {
return -1;
}
return 0;
};
// sort keys (sentence lengths) DESC
$keys = array_keys($byWordCount);
sort($keys);
$sortedLengths = array_reverse($keys);
// built final array sorted by 1) sentence length DESC 2) averaged word length DESC
$sortedKeywords = array();
foreach ($sortedLengths as $length) {
$phrases = $byWordCount[$length];
usort($phrases, $sortByWordLen);
$sortedKeywords = array_merge($sortedKeywords, $phrases);
}
return $sortedKeywords;
}
var_dump(sortKeywords(array(
'foo bar',
'foobar',
'foofoo bar'
'foo',
'foofoo barbar'
)));
- Output for 5.4.0 - 5.4.35
- Parse error: syntax error, unexpected ''foo'' (T_CONSTANT_ENCAPSED_STRING), expecting ')' in /in/srk9H on line 68
Process exited with code 255. - Output for 5.3.0 - 5.3.29
- Parse error: syntax error, unexpected T_CONSTANT_ENCAPSED_STRING, expecting ')' in /in/srk9H on line 68
Process exited with code 255. - Output for 5.1.0 - 5.1.6, 5.2.0 - 5.2.17
- Parse error: syntax error, unexpected T_FUNCTION in /in/srk9H on line 22
Process exited with code 255. - Output for 5.0.0 - 5.0.5
- Parse error: parse error, unexpected T_ARRAY, expecting '&' or T_VARIABLE in /in/srk9H on line 3
Process exited with code 255. - Output for 4.4.2 - 4.4.9
- Parse error: syntax error, unexpected T_ARRAY, expecting ')' in /in/srk9H on line 3
Process exited with code 255. - Output for 4.3.0 - 4.3.1, 4.3.5 - 4.3.11, 4.4.0 - 4.4.1
- Parse error: parse error, unexpected T_ARRAY, expecting ')' in /in/srk9H on line 3
Process exited with code 255. - Output for 4.3.2 - 4.3.4
- Parse error: parse error, expecting `')'' in /in/srk9H on line 3
Process exited with code 255.
preferences:
225.11 ms | 1395 KiB | 125 Q