I've got a website running on a pretty old PHP 5.6.38 installation... and I've now taken the plunge to move it onto the latest XAMPP version (with PHP 8.0.3).
Unsurprisingly, there's a few changes necessary, but the one I can't seem to get sorted is the one relating to the deprecated "create_function" function. I used this to allow me to dynamically sort associative arrays by one or more key names... for example :
usort($myarray, create_function('$a,$b', get_usort_function('field2 ASC, field5 ASC')));
Now, I've read that I should be using an anonymous function, so have changed the code to be as follows...
usort($myarray, function($a,$b) { get_usort_function('field2 ASC, field5 ASC'); } );
The get_usort_function is used to create the text required for the comparisons - so for the example above it would return something like...
$field2=compare_ints($a['field2'], $b['field2']); if($field2==0){return compare_ints($a['field5'], $b['field5']);}else{return $field2;}
Now, in the PHP8 version then the anonymous function isn't working - BUT if I hardcode the string that get_usort_function returns then it DOES work. Am I missing something?
A simplified example of this in action is as follows...
<?php
function compare_ints($val1, $val2)
{
return $val1 <=> $val2;
}
function dynamic_create_usort_function()
{
$str='return compare_ints($a[' . "'" . 'id' . "'" . '], $b[' . "'" . 'id' . "'" . ']);';
return $str;
}
$a1 = array( 'id' => 9, 'name' => 'Andy');
$a2 = array( 'id' => 5, 'name' => 'Bob');
$a = array($a1, $a2);
$s = dynamic_create_usort_function();
print "\n\n***$s***\n\n";
print_r($a);
usort($a, function($a,$b) { dynamic_create_usort_function(); } );
print_r($a);
usort($a, function($a,$b) { return compare_ints($a['id'], $b['id']); } );
print_r($a);
?>
The above example gives output of...
***return compare_ints($a['id'], $b['id']);***
Array
(
[0] => Array
(
[id] => 9
[name] => Andy
)
[1] => Array
(
[id] => 5
[name] => Bob
)
)
Array
(
[0] => Array
(
[id] => 9
[name] => Andy
)
[1] => Array
(
[id] => 5
[name] => Bob
)
)
Array
(
[0] => Array
(
[id] => 5
[name] => Bob
)
[1] => Array
(
[id] => 9
[name] => Andy
)
)
I'd really like to solve this as my website makes a lot of use of this usort function! So, obviously the least amount of rework that'll be needed is the dream...
Thanks in advance, Darren