I am trying to create a simple function to sort an array with usort and I don't understand what's wrong with my code.
For the test, I want to order by the field 'str' in "descending" order.
My array for the test :
$tabCustom = array(
0 => array(
'str' => 'cccc',
'nb' => 1
),
1 => array(
'str' => 'aaaa',
'nb' => 3
),
2 => array(
'str' => 'bbb',
'nb' => 2
)
);
Here the code who works well without custom function :
usort($tabCustom, function($a, $b)
{
$order = 'desc';
if($order == 'asc')
{
return strcasecmp($a['str'], $b['str']);
}
elseif($order == 'desc')
{
return strcasecmp($b['str'], $a['str']);
}
});
The result :
Array
(
[0] => Array
(
[str] => cccc
[nb] => 1
)
[1] => Array
(
[str] => bbb
[nb] => 2
)
[2] => Array
(
[str] => aaaa
[nb] => 3
)
)
And now I try to build a custom function based on the same code :
function arraySort($array, $field, $order = 'asc')
{
usort($array, function($a, $b)
{
global $field;
global $order;
if($order == 'asc')
{
return strcasecmp($a[$field], $b[$field]);
}
elseif($order == 'desc')
{
return strcasecmp($b[$field], $a[$field]);
}
});
}
arraySort($tabCustom, 'str', 'desc');
The wrong result :
Array
(
[0] => Array
(
[str] => cccc
[nb] => 1
)
[1] => Array
(
[str] => bbb
[nb] => 2
)
[2] => Array
(
[str] => aaaa
[nb] => 3
)
)
So I don't understand what's wrong, I have put the global variable for $field and $order because otherwise the code says Undefined variable, but my table sorting doesn't work.
Have you an idea about the problem?
Thanks :)