문제

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']);
}
도움이 되었습니까?

해결책 2

Try implementing the function anonymously:

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

return $content;

다른 팁

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

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top