I need to sort a multidimensional array by a the column reference
. The problem is that the reference
has ‘-‘, so reference
is alphanumeric.
Example:
array(
0 =>['other_value' => y, 'reference' => '423-52', 'other_value' => x],
1 =>['other_value' => y, 'reference' => '223-52', 'other_value' => x],
2 =>['other_value' => y, 'reference' => '5423-52', 'other_value' => x],
3 =>['other_value' => y, 'reference' => '823-52', 'other_value' => x],
4 =>['other_value' => y, 'reference' => '123-52', 'other_value' => x]
)
Expected sorted result:
array(
0 =>['other_value' => y, 'reference' => '123-52', 'other_value' => x],
1 =>['other_value' => y, 'reference' => '223-52', 'other_value' => x],
2 =>['other_value' => y, 'reference' => '423-52', 'other_value' => x],
3 =>['other_value' => y, 'reference' => '823-52', 'other_value' => x],
4 =>['other_value' => y, 'reference' => '5423-52', 'other_value' => x]
)
2
Answers
Finally, I use the function usort to call a method which has a comparing function (gmp_cmp) exploded by '-' and getting the first position, but this method only sort by the reference first part.
Using
filter_var
withFILTER_SANITIZE_NUMBER_INT
to transform value to (positive/negative) integer value, and the spaceship operator<=>
for comparison.See the code in action at https://3v4l.org/OZ7VD