在一个电报机器人消息中使用 foreach 循环

use foreach loop inside one telegram bot message

我有一个代码可以从 mysql 数据库中获取列表并将结果发送给电报机器人中的用户。该代码没有任何问题 - 但它会为每个结果发送一条消息。这就是问题所在,它会淹没服务器。我试图更改代码以在一条消息文本中发送所有结果,但它只发送最后一个结果。 主要代码(没有变化):

$sql92 = "SELECT name, price, link FROM packages";
$result92 = mysqli_query($conn, $sql92);
if (mysqli_num_rows($result92) > 0) {

    foreach($result92 as $row) {
       $packname = $row["name"];
       $packprice = $row["price"]; 
       $packlink = $row["link"];

        $amount = $packprice/100;
    $amount = $amount*80;
       $packtext = "
       $lang_packname => $packname 
       $lang_packprice => $amount $lang_sambol 
       $lang_packdesc => $packlink";
       var_dump(makereq('sendMessage',[
            'chat_id'=>$update->message->chat->id,
            'text'=>"$packtext ",
            'parse_mode'=>'MarkDown',
            'reply_markup'=>json_encode([
                'keyboard'=>[
                [
                ['text'=>"$lang_back"]
              ]
            ],
            'resize_keyboard'=>true
        ])
    ]));
    }


}

@waterloomatt 的回答

它工作正常!

You need to concatenate the message string inside the loop. Currently, you're overwriting it each time. Simply, put a single . (dot) directly before the =. Ex. ... $packtext .=. This, however, will simply glue multiple strings together so the formatting of the message will likely be wrong but you should be able to make progress.

$sql92 = "SELECT name, price, link FROM packages";
$result92 = mysqli_query($conn, $sql92);
if (mysqli_num_rows($result92) > 0) {

    foreach($result92 as $row) {
       $packname = $row["name"];
       $packprice = $row["price"]; 
       $packlink = $row["link"];

        $amount = $packprice/100;
    $amount = $amount*80;
       $packtext .= "
       $lang_packname => $packname 
       $lang_packprice => $amount $lang_sambol 
       $lang_packdesc => $packlink";

    }
 var_dump(makereq('sendMessage',[
            'chat_id'=>$update->message->chat->id,
            'text'=>"$packtext ",
            'parse_mode'=>'MarkDown',
            'reply_markup'=>json_encode([
                'keyboard'=>[
                [
                ['text'=>"$lang_back"]
              ]
            ],
            'resize_keyboard'=>true
        ])
    ]));

}