0

There are a few posts here on SO that concern with sorting multidimensional arrays in php and I can get it to work fine when using:

usort($list, function($a, $b)
            {
                return $a['content_id'] <=> $b['content_id'];
            }
        );

But I can't find any reference to using a variable to sort with. When I try to use one, I get an error. eg in this example:

    $sortVariable='content_id';
    usort($list, function($a, $b)
            {
                return $a[$sortVariable] <=> $b[$sortVariable];
            }
        );

It doesn't work and I am not sure why - I get the 'Undefined variable' error. Looking for help, thanks

John Conde
  • 217,595
  • 99
  • 455
  • 496
gavin stanley
  • 1,082
  • 2
  • 13
  • 28

1 Answers1

1

That's due to variable scope. $sortVariable is not available inside of your function. To make it available to your closure use the use language construct:

$sortVariable='content_id';
usort($list, function($a, $b) use ($sortVariable) {
    return $a[$sortVariable] <=> $b[$sortVariable];
});
John Conde
  • 217,595
  • 99
  • 455
  • 496