I'm rewriting an old script that spits out the most popular content using usort.
For some reason, the output of my usort isn't actually sorted.
I'm using php 5.5 (please disregard the use of the depreciated mysql_ function, that is part of the reason I am rewriting this script).
//store data in array
$sort_array = array();
while($row = mysql_fetch_assoc($result)) {
//calculate age
$age = (strtotime("now") - strtotime($row["DATE"]))/86400;//86400 converts seconds to days
//calculate "effective views" via gaussian distribution shown below
//y = e^(-(k * x)^2) where k is below
$K = 0.1665109222315395512706329289790402095261177704528881;//solved for a half-life of 5 days
$effective_views = round($row["VIEWS"] * exp(-pow( $K * $age, 2)));
//store data
$article = new stdClass;
//$article->id = $row["ID"];
$article->effective_views = $effective_views;
//$article->title = $row["TITLE"];
//$article->author = $row["AUTHOR"];
$sort_array[] = $article;
}
//sort array based on effective views
usort(
$sort_array,
function($a, $b) {
return -strcmp($a->effective_views, $b->effective_views);
}
);
echo "<pre>";
print_r($sort_array);
The output should be sorted on effective_views in descending order, however, it is not.
Here is an output dump:
Please inform me what I am doing wrong here.