问题
How can I use usort
to sort an associative array inside a symfony2
controller?
//sort
function compare($a, $b)
{
return strnatcmp($a['sort'], $b['sort']);
}
usort($content, 'compare');
That gives me the following error:
Warning: usort() expects parameter 2 to be a valid callback, function 'compare' not found or invalid function name
as does putting it in its own private function like this
// sort
usort($content, '$this->compare');
return $content;
}
//sort
private function compare($a, $b)
{
return strnatcmp($a['sort'], $b['sort']);
}
this no change
// sort
usort($content, 'compare');
return $content;
}
//sort
private function compare($a, $b)
{
return strnatcmp($a['sort'], $b['sort']);
}
回答1:
Try implementing the function anonymously:
usort($content, function ($a, $b) {
return strnatcmp($a['sort'], $b['sort']);
});
return $content;
回答2:
usort($content, array($this, 'compare'));
This is how you pass an object method as a call-back. See callbacks for examples.
来源:https://stackoverflow.com/questions/14281306/using-usort-with-associative-array-inside-symfony2-controller