开发者

Question about PHP usort function

开发者 https://www.devze.com 2023-01-17 16:54 出处:网络
i\'ve got a PHP script where i rearange a multidimensional array with the use of the usort()-function.

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?


May be try this by send index of subkey i.e. grade instead of name of subkey .


With 5.3 you can do it like this:

function create_sort($key)
{
    return function($x,$y) use($key)
    {
        return $x[$key] - $y[$key];
    };
}
$sorter = create_sort('name');
usort($arr, $sorter);


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.

function sort_movies($arr,$val){
    function cmp($x, $y)
    {
        global $val; // <---------------------------------
        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");

http://php.net/manual/en/language.variables.scope.php

0

精彩评论

暂无评论...
验证码 换一张
取 消