1

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.

1 Answer 1

3

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]);
});
Sign up to request clarification or add additional context in comments.

3 Comments

Interesting. Thanks for the input. I tried your solution, but $sortBy is still not used.If I replaceit by for instance "name" it works, but when I use $sortBy, nothing happens. and $sortBy does equal name ...
I got it to work using the old code, but indeed without the quotes, and by making $sortBy global. Something of a scope issue like you pointed out .. but apparently your solution still has that scope issue? curious to what you think about it ..
$sortBy needs to be available in the same scope as where you call usort. You can't pass $sortBy to the anonymous function unless the place where you declare that function has access to this variable. If you're calling usort in a scope other than the global one (ie a function, or a method), then that's why it's not working. I'd need to see more code to tell for sure

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.