Question

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']);
}
Was it helpful?

Solution 2

Try implementing the function anonymously:

usort($content, function ($a, $b) {
    return strnatcmp($a['sort'], $b['sort']);
});

return $content;

OTHER TIPS

usort($content, array($this, 'compare'));

This is how you pass an object method as a call-back. See callbacks for examples.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top