I’ve found some solutions to a sorting problem I’ve been having, but the code uses anonymous functions in PHP. Im using version 5.2.17 and I believe anonymous functions are not supported.
How would I change the following blocks of code so I can use them in PHP 5.2.17
$keys = array_flip($order);
usort($items, function($a, $b) use($keys)
{
return $keys[$a['id']] - $keys[$b['id']];
});
from PHP sort multidimensional array by other array
And
$sorted = array_map(function($v) use ($data) {
return $data[$v - 1];
}, $order);
from PHP – Sort multi-dimensional array by another array
UPDATE:
One of the problems is I’m not sure how the variables $a, $b and $v are used. So I’m not sure how to create normal functions, thus bypassing the anon functions.
Both of the anonymous functions make use of the
useclause to pass variables into the local scope.You can achieve the same with object methods in which the objects have those variables as properties.
Inside the object method you then can access these.
An exemplary mapping object then could look like:
As you can see it has the same functionality but just written in PHP 5.2 syntax.
And it’s usage:
And that’s how it works. Callbacks for object methods are always written in form of an
arraywith two members, the first one is the object instance, and the second one is the name of the object method.Naturally you can extend this an put the mapping function into the mapping object, so it’s more straight forward:
New usage:
As you can see this might make the usage a bit more straight forward. I must admit, my method naming is not really brilliant here, so I leave some room for your improvements.
Another benefit is, you can make the visibility of the callback method private then.
The situation with passing the data to work with in the callback as a parameter to the mapping function. That is because you wrote you already have a class that you want to make use of, but you can not touch the constructor. So the given example is a bit short.
Here is another example without using the constructor, I removed it:
As you can see, the constructor is not needed any longer to pass the
$data, but instead it’s just passed into themap()method as an additional parameter. Usage:As you can see, how you set the private member variable is up to you. Do what fits the job.