对于我正在构建的 Telegram 机器人,我想根据返回的 PHP PDO 记录集Telegram API docs动态返回内联按钮。
硬编码一段好的函数代码如下所示。这是确认工作。它返回两行按钮。第一行包含两个按钮,第二行包含两个按钮。
$reply = "Some message to show before the buttons";
$keyb = array('inline_keyboard' => array(
array(
array('text'=>'Link text', 'callback_data'=>'/command'),
array('text'=>"Link text", 'callback_data'=>'/command')
),
array(
array('text'=>'Link text', 'callback_data'=>'/command'),
array('text'=>'Link text', 'callback_data'=>'/command')
)
)
);
$replyMarkup = json_encode($keyb);
sendMessage($chatID, $reply, $replyMarkup);
到目前为止,一切都很好。但现在我想在给定 PHP 记录集的情况下动态填充这些按钮。
下面确实返回了所需的按钮,但我不知道如何在两个按钮之后指定一个截止点来创建第二行。在下面的格式中,所有按钮最终都在一行中。即使记录集返回 5 个结果。
$reply = "Some message to show before the buttons";
$i=0;
// Loop through all results to create individual buttons
foreach ($stmt as $row)
{
$options[] = array('text'=>urlencode($row['title']), 'callback_data'=>'/x');
$i++;
}
$keyb = array('inline_keyboard' => array( $options ));
$replyMarkup = json_encode($keyb);
sendMessage($chatID, $reply, $replyMarkup);
我考虑过使用带有模运算符($i%2=1)的 if 语句,但不知道如何处理定义行的父数组()...
...
if($i%2=1)
{
$options[]="array("; // <-- Setting an array as a value will obviously fail
}
... remaining code
很高兴听到任何可能对我有所帮助的想法!
谢谢。