tags:

views:

64

answers:

3

Hi! 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?

A: 

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

Chinmayee
A: 

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);
Dennis Haarbrink
my server is only 5.2 unfortunately
Volmar
A: 

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

steven_desu