sineverba sineverba - 1 month ago 5
PHP Question

Sort sub array descending (or create it in another mode)

I'm getting, for pagination, previous (if they exists) 5 page respect of current page.

$k = 0;
for ($i=$requested_page-1;$i>=1;$i--) {

if ($k<$range_pagination) {

$result['range_pagination']['under'][] = $i;

}
$k++;

}


But array resulting is:

array(2) {
["under"]=>
array(5) {
[0]=>
int(14)
[1]=>
int(13)
[2]=>
int(12)
[3]=>
int(11)
[4]=>
int(10)
}[...]


Printing them in HTML results in not-so-beautiful way

enter image description here

But must be

enter image description here

I did try

rsort($result['range_pagination']['under']);


without change.

So, how can I sort the array OR create in another way?

Thank you very much.

Answer

Maybe do this?

for ($i=$requested_page-5;$i<=$requested_page;$i++) {
    if ($i >= 1  && $i < $range_pagination)
    {
        $result['range_pagination']['under'][] = $i;
    }
}

You'll need the $range_pagination to make sure it won't echo more pages than it has. It put it there assuming this is your total_pages number

This will output, for example, if your $requested_page equals 20,

15 16 17 18 19 20

This could make it look better:

for ($i=$requested_page-2;$i<=$requested_page+2;$i++) {
    if ($i >= 1  && $i <= $range_pagination)
    {
        if ($i == $requested_page)
            echo "<b> " . $i . " </b>";
        else
            echo " " . $i . " ";
    }
}

It will look like this: https://ideone.com/dH3tM0

The output would be, for page 1:

1 2 3

page 10:

8 9 10 11 12

last page

28 29 30

Comments