0

This code snippet:

$inline_keyboard = new InlineKeyboard([
    ['text' => 'valueA', 'callback_data' => 'valueA'],
], [
    ['text' => 'valueB', 'callback_data' => 'valueB'],
]);

produces in my telegramm bot the following inline keyboard:

telegram output

So far so good... But instead of hardcoding the values, I want to produce the same output with values from an array (database query).

I tried with something like this:

$dbValues = array("valueA", "valueB");

foreach ($dbValues as $value)
{
    $inline_keyboard .= new InlineKeyboard([
        ['text' => "$value", 'callback_data' => "$value"],
    ]);
}

But this fails... I think because I don't have to run a "new" instance in each iteration?

Thanks for helping!

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Deltahost
  • 107
  • 3
  • 11

2 Answers2

1

You can't concatenation object like string. you can go another way, build the array, and after send array to InlineKeyboard

$dbValues = array("valueA", "valueB");
foreach ($dbValues as $value)
{
    $inline_keyboard[] = [['text' => "$value", 'callback_data' => "$value"]];
}

$inline_keyboard = new InlineKeyboard(...$inline_keyboard);

Further details see "New Keyboard structure and how to pass dynamic arguments" from the php-telegram-bot wiki.

segFault
  • 3,887
  • 1
  • 19
  • 31
Mike Foxtech
  • 1,633
  • 1
  • 6
  • 7
  • 1
    It is almost what I have searched for. But I think the nesting is now not correct. The inline keyboard buttons are now horizontaly not verticaly scaled... see: https://imgur.com/a/2xaORWj – Deltahost Apr 20 '20 at 21:53
  • I get this error: "PHP message: PHP Warning: array_key_exists() expects parameter 2 to be array, boolean given in .../vendor/longman/telegram-bot/src/Entities/Entity.php on line 41 PHP message: PHP Notice: Undefined property: Longman\TelegramBot\Entities\InlineKeyboard::$inline_keyboard in .../vendor/longman/telegram-bot/src/Entities/Keyboard.php on line 42 PHP message: PHP Warning: array_filter() expects parameter 1 to be array, null given in .../vendor/longman/telegram-bot/src/Entities/Keyboard.php on line 42" – Deltahost Apr 21 '20 at 19:51
  • If you wan't to study the entities you can find them here: https://github.com/php-telegram-bot/core/tree/master/src/Entities – Deltahost Apr 21 '20 at 19:52
0

To get a horizontal keyboard you can use this code snippet:

$dbValues = array("valueA", "valueB");
foreach ($dbValues as $value)
{
    $inline_keyboard[] = ['text' => "$value", 'callback_data' => "$value"];
}

$inline_keyboard = new InlineKeyboard($inline_keyboard);
Deltahost
  • 107
  • 3
  • 11