K
K
Kurusa2018-05-21 23:24:39
PHP
Kurusa, 2018-05-21 23:24:39

Telegram, php how to write a pagination algorithm?

I have such a pagination algorithm for inline_keyboard that builds 2 columns of 6 elements, and if there are more than 12 but less than 24 elements (I didn’t have more than 24 before), I manually checked this and duplicated the code:

while ($row = mysqli_fetch_assoc($result)) {

        $one_row[$cnt] = [
            "text" => $row["test"],
            "callback_data" => "test"
        ];
        $cnt++;

        if ($cnt == 2) {
            $buttons[] = $one_row;
            $one_row = [];
            $cnt = 0;
        }
    }

But he turned out to be very incomplete, because if there are, for example, not 14, but 15 elements, then 15 are eaten. In general, it accepts only a pair of elements and if there is only 1 element, it is not shown. In general, I ask you for help, please. It does not occur to me how to rewrite it normally.
If necessary, I will describe the situation: I have a weather bot and I have reached the stage of filling cities, so the number of elements will be the same, but still this algorithm needs to be made universal and convenient. Help me please

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Entelis, 2018-05-21
@Kurusa

You add data to buttons in an iteration when the number of elements in $one_row == your number of columns (in the particular case 2).
Accordingly, if you have a non-multiple number of data, then there is a stub.
The obvious solution is to check what is in $one_row after the loop and save if necessary.

$columns = 2;

$buttons = [];
$one_row = [];
while ($row = mysqli_fetch_assoc($result)) {
    $one_row[] = [
        "text" => $row["test"],
        "callback_data" => "test"
    ];
    if (count($one_row) == $columns) {
        $buttons[] = $one_row;
        $one_row = [];
    }
}
if (count($one_row) > 0) {
    $buttons[] = $one_row;
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question