0

我有问题。在我的函数中,return 仅显示来自服务器的第一个玩家。我想展示服务器中的所有玩家,但我无法正常工作。这是我的代码:

function players() {
    require_once "inc/SampQueryAPI.php";
    $query = new SampQueryAPI('uh1.ownserv.pl', 25052); // Zmień dane obok! //
    if($query->isOnline())
    {
        $aInformation = $query->getInfo();
        $aServerRules = $query->getRules();
        $aPlayers = $query->getDetailedPlayers();
        if(!is_array($aPlayers) || count($aPlayers) == 0)
        {
            return 'Brak graczy online';
        }
        else
        {
            foreach($aPlayers as $sValue)   
            {
                $playerid = $sValue['playerid'];
                $playername = htmlentities($sValue['nickname']);
                $playerscore = $sValue['score'];
                $playerping = $sValue['ping'];
                return '<li>'.$playername.' (ID: '.$playerid.'), Punkty ('.$playerscore.'), Ping ('.$playerping.')</li>';
            }
        }
    }
}
4

3 回答 3

6

您正在从循环中返回。

相反,您应该连接每次迭代的结果,然后在循环外返回连接的字符串。

例如

$result = "";
foreach($aPlayers as $sValue) {
   # add to $result...
}
return $result
于 2013-01-29T13:26:31.507 回答
2
function players() {

    require_once "inc/SampQueryAPI.php";
    $query = new SampQueryAPI('uh1.ownserv.pl', 25052); // Zmień dane obok! //
    if($query->isOnline())
    {
         $aInformation = $query->getInfo();
         $aServerRules = $query->getRules();
         $aPlayers = $query->getDetailedPlayers();
         if(!is_array($aPlayers) || count($aPlayers) == 0)
         {
             return 'Brak graczy online';
         }
         else
         {
             $ret = '';
             foreach($aPlayers as $sValue)   
             {
                 $playerid = $sValue['playerid'];
                 $playername = htmlentities($sValue['nickname']);
                 $playerscore = $sValue['score'];
                 $playerping = $sValue['ping'];
                 $ret .=    '<li>'.$playername.' (ID: '.$playerid.'), Punkty ('.$playerscore.'), Ping ('.$playerping.')</li>'; 
             }
             return $ret;
          }
      }
  }
于 2013-01-29T13:27:01.183 回答
1

在一个函数中,你只能返回一个值。

尝试创建一个玩家列表,并在所有记录都添加到列表中后返回该列表。在您的情况下,玩家列表将产生一系列玩家

于 2013-01-29T13:26:49.487 回答