using usort with associative array inside symfony2 controller

我只是一个虾纸丫 提交于 2019-12-12 12:33:29

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!