PHP For循环似乎不起作用

问题描述 投票:2回答:4

我正在使用Telegram Bot API和PHP制作一个控制面板来管理我的Telegram Bot。

基本上,我想在一个小聊天框中显示单个用户的每条消息。

由于可能有更多用户向Bot发送了消息,因此我必须检查发件人的user_id是否重复并再次重复,然后为新发件人创建一个新的聊天框。

为了做到这一点,我抓住了result中的数组数量,并做到了这一点:

PRIVATE CODE

正如您在代码开头所看到的,我创建了变量store_id以保存FIRST sender_id,如果再次重复此sender_id,则继续执行for循环,直到$ i小于$ num。

但问题是它根本没有显示任何东西。我的意思是没有错误,没有结果!

这里出了什么问题,我该怎么办?

更新:

PRIVATE CODE

但结果又是:

enter image description here

php telegram telegram-bot php-telegram-bot
4个回答
2
投票

问题是因为您只检查发件人是否已存在或其是新发件人。如果是新的,则将sender_id添加到阵列并打印聊天框。如果它是一个已经存在的发送者,那么你什么都不做并继续。

意味着您正在跳过为ID已存在于数组中的发件人打印消息。

所以现在不要继续使用array_search()之类的

$sender_ids = array();
for($i=0;$i<$num;$i++)
{
    $sender_id = $updateArray["result"][$i]["message"]["from"]["id"];
    if(!(in_array($sender_ids, $sender_ids)))
    {
        $sender_ids[] = $sender_id;
        echo ' CHAT BOX ';
    }
    else
    {
        $key = array_search($sender_ids, $sender_ids);
        // here this $key will be now same for all the messages from same sender id.
        // and you can make logic to group them.
    }
} 

希望我帮助你。 :)


3
投票

问题是因为首先你要分配

$sender_id = $updateArray["result"][$i]["message"]["from"]["id"];

然后你要分配

$store_id = $sender_id;

意味着$store_id将具有$sender_id的确切含量

那你在检查

if($sender_id == $store_id)

这将永远是真的,循环每次都得到continue

这就是为什么屏幕上没有显示任何内容而不是语法错误的原因。

你忘了在$store_id中分配正确的store_id。

希望我能帮助你。祝好运。


1
投票

为什么要将sender_id与store_id进行比较。为了比较它们应该来自不同的来源,然后你会检查它们是否相等。你应该有一种方法来检查sender_id是否已经是他们的。您可以创建一个数组,然后继续将sender_id存储在数组中,但在分配之前,您将检查sender_id是否应该不存在于数组中。如果存在则继续。

$sender_ids = array();

for($i=0;$i<$num;$i++)
{
    $sender_id = $updateArray["result"][$i]["message"]["from"]["id"];
    if(!(in_array($sender_ids, $sender_ids)))
    {
        $sender_ids[] = $sender_id;
        echo ' CHAT BOX ';
    }
    else
    {
        continue;
    }
} 

0
投票

目前还不是很清楚你想要实现什么,但我想以下代码会做到这一点:

$updateArray = json_decode($update, TRUE);

// Initialize $store_id with a value that doesn't appear in the input data
$store_id = NULL;

// foreach is better that for(;;) to iterate over collections
foreach ($updateArray["result"] as $item) {
   // Get the sender of the current item
   $sender_id = $item["message"]["from"]["id"];
   // Use strict comparison to make sure it doesn't match when it shouldn't
   // (f.e. if `$sender_id` is the empty string it is == to NULL but not ===)
   if ($sender_id === $store_id) {
      // It is the same sender as of the previous message; skip this message
      continue;
   } else {
      // This is a new sender; process it...
      echo ' CHAT BOX ';
      // ... and remember it for the next items
      $store_id = $sender_id;
   }
}
© www.soinside.com 2019 - 2024. All rights reserved.