I'm writing customized sort function. Current (non-working) code looks like this:
<?php
function sort_by_key($array, $key) {
function custom_compare ($a, $b) {
if ($a[$key][0] > $b[$key][0]) { return 1; }
else { return -1; }
}
return usort($array, "custom_compare");
}
?>
The problem is that I cannot pass $key variable to custom_compare function. I'd like to avoid using global variables (ugly coding).
Untested, but you could use an anonymous function:
<?php
function sort_by_key($array, $key) {
$custom_compare = function ($a, $b) use ($key) {
if ($a[$key][0] > $b[$key][0]) { return 1; }
else { return -1; }
};
return usort($array, $custom_compare);
}
Based on a small modification of your existing function.
Further your function still needs a small change:
<?php
function sort_by_key(&$array, $key) {
$custom_compare = function ($a, $b) use ($key) {
if ($a[$key][0] > $b[$key][0]) {
return 1;
} else {
return -1;
}
};
usort($array, $custom_compare);
}
$array = array(
array(
'foo' => array(
2
)
),
array(
'foo' => array(
3
)
),
array(
'foo' => array(
1
)
)
);
sort_by_key($array, 'foo');
var_export($array);
Output:
array (
0 =>
array (
'foo' =>
array (
0 => 1,
),
),
1 =>
array (
'foo' =>
array (
0 => 2,
),
),
2 =>
array (
'foo' =>
array (
0 => 3,
),
),
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With