douhu4692 2015-04-11 21:37 采纳率: 100%
浏览 24
已采纳

PHP关联数组和未设置[关闭]

I'm creating an irc bot and I have an array for Channels ($BotChannels = ['Channel' => [], 'Commands' => [], 'Type' => []];) The bot check on mysql when a new channel is added and when a old channel is removed and when the channel is removed i use a for to catch the channel position but when I use the unset function to remove the channel from array i always get an empty space on array code below.

if(count($BotChannels['Channel']) > 0) {
            for($i = 0; $i < count($BotChannels['Channel']); $i++) {
                if(!in_array($BotChannels['Channel'][$i], $TempChan)) {
                    IrcMsg($BotChannels['Channel'][$i], 'Channel removed from database, leaving.');
                    PartChannel($BotChannels['Channel'][$i]);
                    unset($BotChannels['Channel'][$i], $BotChannels['Commands'][$i] ,$BotChannels['Type'][$i]);
                }
            }
            unset($TempChan);
        }
  • 写回答

1条回答 默认 最新

  • dongshuogai2343 2015-04-11 23:07
    关注

    First and foremost, your array structure of "$BotChannels" does not look like it can support holding SQL results man.

    Therefore I would recommend the structure to be like the one below.

    $BotChannels = [
      'key' => [  # "key" is your variable $i
         'Channel' => [],
         'Commands' => [],
         'Type' => []
      ],
    ];
    

    And as for your Algorithm

    if(count($BotChannels) > 0) {
       foreach (array_keys($BotChannels) as $key) { 
          if(!in_array($key, $TempChan)) {
          IrcMsg($key, 'Channel removed from database, leaving.');
          PartChannel($key);
          unset($BotChannels[$key]);
       }
       unset($TempChan);
    }
    

    If you insist on not changing your array "$BotChannels", then please make sure the SQL results are being populated exactly, how you want it to.

    echo '<pre>'.print_r($BotChannels, 1).'</pre>'; # TIP
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改