I have the following values in an array,
$values = array(
"1/4x1/4x1",
"1/2x1/2x1",
"3/4x3/4x1",
"1/4x1/4x2",
"1/2x1/2x2",
"3/4x3/4x2",
"1x1x1",
"1x2x1",
"2x1x1"
);
Considering the numbers in between 'x', I want the ascending order of the values as the following,
$values = array(
"1/4x1/4x1",
"1/4x1/4x2",
"1/2x1/2x1",
"1/2x1/2x2",
"3/4x3/4x1",
"3/4x3/4x2",
"1x1x1",
"1x2x1",
"2x1x1"
);
I'm new to PHP. Are there any specific functions for this? If not, please help with a way to find a solution. Thanks.
It is a bit complex, but you can avoid using eval
:
// Transpose resulting 2x2 matrix using array_map behavior of
// tacking an arbitrary number of arrays and zipping elements, when null
// giving as a callback.
$evaluated = array_map(null, ...array_map(function ($factors) {
return array_map(function ($factor) {
// Explode fraction (into array with two elements)
// and destruct it into variables.
// `@` will silent the notice if not a fraction given (array with one
// element).
@list($dividend, $divisor) = explode('/', $factor); // **
// If divisor is given then calculate a fraction.
return $divisor
? floatval($dividend) / floatval($divisor)
: floatval($dividend);
}, explode('x', $factors));
}, $values));
// Assign values array by reference as a last element.
$evaluated[] =& $values;
// Unpack all arrays (three columns of fractions and given array) and pass
// them to `array_multisort` function, that will sort in turns by each of
// the columns.
array_multisort(...$evaluated);
print_r($values);
So, basically, we map each item from the array into an array of calculated fractions and then transpose this array to end up with three arrays representing columns. Then we pass this three array along with given array into array_multisort
, that takes the given array by reference and reorders it as we want.
Here is the demo.