I have an array sorted as follows:
Array (
[0] => Array (
[x] => 0
[y] => 1
)
[1] => Array (
[x] => 210
[y] => 1
)
[2] => Array (
[x] => 440
[y] => 1
)
[3] => Array (
[x] => 210
[y] => 2
)
[4] => Array (
[x] => 0
[y] => 2
)
)
I have already sorted with the value y using rsort
:
rsort($packagesinf, 'my_sortY');
print_r($packagesinf);
function my_sortY($a, $b)
{
if ($a->y> $b->y) {
return -1;
} else if ($a->y< $b->y) {
return 1;
} else {
return 0;
}
}
I would liketo sort for each different Y, the X values in ascending order. In my case, it would be: [0]>[1]>[2]>[4]>[3]
.
DO you have any idea how to do it taking into account that the priority is first the Y and then the X?
EDIT: So now I have modified the code according to the solutions proposed:
function my_sortYX($a, $b)
{
if ($a->y > $b->y) {
return 1;
} else if ($a->y < $b->y) {
return -1;
} else {
if ($a->x > $b->x) {
return 1;
} else if ($a->x < $b->x) {
return -1;
} else {
return 0;
}
}
}
function sortByY($a, $b) {
return $a['y'] - $b['y'];
}
echo json_encode($packagesinf);
echo nl2br("\n");
echo nl2br("\n");
echo 'my_sortYX';
echo nl2br("\n");
usort($packagesinf, 'my_sortYX');
echo json_encode($packagesinf);
echo nl2br("\n");
echo nl2br("\n");
echo 'sortByY';
echo nl2br("\n");
usort($packagesinf, 'sortByY');
echo json_encode($packagesinf);
echo nl2br("\n");
echo nl2br("\n");
Which now is sorting correctly for Y with the function sortByY, but I'm still facing the same problem of sorting also for x...
This is the what I recieve from the echo:
[{"x":0,"y":1},{"x":210,"y":1},{"x":440,"y":1},{"x":210,"y":2},{"x":0,"y":2},{"x":30,"y":3},{"x":420,"y":1}]
my_sortYX
[{"x":30,"y":3},{"x":420,"y":1},{"x":0,"y":2},{"x":210,"y":2},{"x":210,"y":1},{"x":440,"y":1},{"x":0,"y":1}]
sortByY
[{"x":440,"y":1},{"x":0,"y":1},{"x":420,"y":1},{"x":210,"y":1},{"x":210,"y":2},{"x":0,"y":2},{"x":30,"y":3}]
So my_sortYX it is still not working properly, only the sortByY...