/    Sign up×
Community /Pin to ProfileBookmark

usort() with callback in a class…

I am creating a simple CMS.
Here’s the situation: I have an array which looks like:

[code]
Array
(
[0] => Array
(
[name] => download
[size] => [dir]
[href] => ?action=browse&f=&p=download/
)

[1] => Array
(
[name] => files
[size] => [dir]
[href] => ?action=browse&f=&p=files/
)

[2] => Array
(
[name] => images
[size] => [dir]
[href] => ?action=browse&f=&p=images/
)
)
[/code]

And I want to sort it by name. So I wrote this function and put it inside the main class named CMSEngine:

[code]
function cb_sort($a, $b) {
return strcasecmp($a[‘name’], $b[‘name’]);
}
[/code]

And then tried all of these combinations, but none worked:

[code]
usort($aDirs, CMSEngine::cb_sort);
usort($aDirs, $this->cb_sort); // Yes, this happens inside another function in the same class.
usort($aDirs, “CMSEngine::cb_sort”);
usort($aDirs, “$this->cb_sort”);
usort($aDirs, “$this->cb_sort”);
[/code]

Is there any way to do this?

to post a comment
PHP

4 Comments(s)

Copy linkTweet thisAlerts:
@bokehSep 23.2007 — A method of an instantiated object is passed as an array containing an object as the element with index 0 and a method name as the element with index 1.
[code=php]usort($aDirs, array($this,'cb_sort')); // Called from another function in the same class.[/code]
[code=php]usort($aDirs, array($obj,'cb_sort')); // Called from procedural code (outside the class).[/code]

Static class methods can also be passed without instantiating an object of that class by passing the class name instead of an object as the element with index 0.
[code=php]usort($aDirs, array('ClassNameHere','cb_sort'));[/code]
Copy linkTweet thisAlerts:
@ZnupiauthorSep 23.2007 — Oh yeah, I didn't scroll that down on the usort manual page ?, thanks! ?
Copy linkTweet thisAlerts:
@bokehSep 23.2007 — Maybe you would have had better luck with the manual if you had thought what you were trying to extract from it. Your question was about callback syntax, not usort.
Copy linkTweet thisAlerts:
@ZnupiauthorSep 23.2007 — Good info, thanks again ?
×

Success!

Help @Znupi spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.15,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...