Reputation: 57
I have an array consisting of 4 fields.
$retval[] = array(
"name" => "$dir$entry/",
"type" => filetype("$dir$entry"),
"size" => 0,
"lastmod" => filemtime("$dir$entry")
);
I want to sort this array depending on a variable, which contains either 1 of the 4 field (eg: type, name etc)
$sortBy = $_GET['sortBy'];
This function should use the $sortBy variable:
function compare_field($a, $b){
return strnatcmp($a["'.$sortBy.'"], $b["'.$sortBy.'"])
}
And is called like this:
usort($retval, "compare_field");
But the construction doesn't work ..
Hope someone can point me in the right direction, being the obvious newby I am.
Upvotes: 1
Views: 53
Reputation: 76413
First, you're sorting by a key that is actually: '..'
, not the value of $sortBy
. You're trying to use a variables value as the key, to do that, you don't need to mess around with quotes, just write $arrayName[$keyVariable]
. That's it.
Second is that compare_field
had no access to the $sortBy
variable. That variable is local to the scope where it was created, or it's a global variable. Either way, functions don't have access to it.
If you want the usort
callback to have access to the $sortBy
variable, the easiest way would be to use a closure (anonymous function) as callback:
usort($retval, function ($a, $b) use ($sortBy) {
return strnatcmp($a[$sortBy], $b[$sortBy]);
});
Upvotes: 3