简体   繁体   中英

using usort with associative array inside symfony2 controller

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']);
}
usort($content, array($this, 'compare'));

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

Try implementing the function anonymously:

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

return $content;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM