关于PHP usort函数的问题
我有一个 PHP 脚本,其中使用 usort() 函数重新排列多维数组。
这是数组 $arr 的示例数组(print_r-output)
Array
(
[3] => Array
(
[name] => Bjudningen
[grade] => 5
[grade_type] => calculated
[orgname] => LInvitation
[id] => 13975
)
[0] => Array
(
[name] => Coeur fidèle
[grade] => 3
[grade_type] => calculated
[orgname] => Coeur fidèle
[id] => 8075
)
[2] => Array
(
[name] => Dawsonpatrullen
[grade] => 5
[grade_type] => calculated
[orgname] => The Dawson Patrol
[id] => 13083
)
)
这是我的 PHP 脚本
function sort_movies($arr,$val){
function cmp($x, $y)
{
if ( $x[$val] == $y[$val] )
return 0;
else if ( $x[$val] < $y[$val] )
return -1;
else
return 1;
}
usort($arr, 'cmp');
return $arr;
}
$sorted = sort_movies($arr,"grade");
我希望能够对不同子键(即名称、年级、id)上的数组进行排序,但它不能按我的方式工作执行上面的操作。但是,如果我将排序电影函数中的 $val
更改为值 "grade"
它确实有效,因此由于某种原因,它不允许我发送可用的作为排序参数。
我做错了什么?
i've got a PHP script where i rearange a multidimensional array with the use of the usort()-function.
this is a sample array (print_r-output) of array $arr
Array
(
[3] => Array
(
[name] => Bjudningen
[grade] => 5
[grade_type] => calculated
[orgname] => LInvitation
[id] => 13975
)
[0] => Array
(
[name] => Coeur fidèle
[grade] => 3
[grade_type] => calculated
[orgname] => Coeur fidèle
[id] => 8075
)
[2] => Array
(
[name] => Dawsonpatrullen
[grade] => 5
[grade_type] => calculated
[orgname] => The Dawson Patrol
[id] => 13083
)
)
And this is my PHP script
function sort_movies($arr,$val){
function cmp($x, $y)
{
if ( $x[$val] == $y[$val] )
return 0;
else if ( $x[$val] < $y[$val] )
return -1;
else
return 1;
}
usort($arr, 'cmp');
return $arr;
}
$sorted = sort_movies($arr,"grade");
I want to be able to sort the array on different subkeys (i.e. name, grade,id), but it doesn't work the way i do it above. however if i change $val
in the sort movies function to the value "grade"
it does work, so for some reason it won't allow me to send in a vaiable as the sort parameter.
what is it i'm doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
可以通过发送子项索引(即等级)而不是子项名称来尝试此操作。
May be try this by send index of subkey i.e. grade instead of name of subkey .
在 5.3 中你可以这样做:
With 5.3 you can do it like this:
问题是 $val 仅在函数 sort_movies() 的范围内可用,而不在 cmp() 的范围内可用。您只需将其声明为全局即可。这会将其拉入范围,以便您可以在 cmp() 函数中使用它。
http://php.net/manual/en/language.variables.scope.php
The problem is that $val is only available within the scope of the function sort_movies(), not in the scope of cmp(). You need to just declare it as global. This will pull it into scope so you can use it within the cmp() function.
http://php.net/manual/en/language.variables.scope.php