drju37335 2016-04-25 17:58
浏览 54

需要循环遍历一个动态大小的PHP数组

I have a poker game where 2 to 5 players join the game before the start button is pressed.They are added to a players arrays array as objects containing userid and username.

I need to populate my currentUser with the player object then on a button click(call/raise/fold) move to the next in the array to give illusion of the game moving seat to seat

When the start button is clicked i set the current user to the first element in the array which works.

$thisPokergame->State['CurrentUser'] = RESET($thisPokergame->State['Players']);

then im trying this

    if($thisPokergame->State['CurrentUser'] == end($thisPokergame->State['Players']))
    {
        $thisPokergame->State['CurrentUser'] = reset($thisPokergame->State['Players']);
    }
    else{
        $thisPokergame->State['CurrentUser'] = next($thisPokergame->State['Players']);;
    }

the if works by itself e.g if its the last player in the array it set current user to the the first and so does the statement inside the else.

When i put them together i get currentuser as false and i cant see the reason. anyone have a solution or better way to do it?

  • 写回答

1条回答 默认 最新

  • doureng6738 2016-04-25 18:09
    关注

    You are having this problem because the functions you're using move the internal array pointer.

    You will always get false in the else part of your conditional, because when you use end($thisPokergame->State['Players']) in the if condition, you have moved the internal array pointer to the the last element. Then in the else when you do next($thisPokergame->State['Players']), you get false because there are no more elements.

    Without knowing for sure what is in CurrentUser or Players I'm not certain how this could be handled instead, but I think this might work:

    $player = array_shift($thisPokergame->State['Players']);
    $thisPokergame->State['Players'][] = $player;
    $thisPokergame->State['CurrentUser'] = reset($thisPokergame->State['Players']);
    

    Basically just rotate the first player in the list of players to the end of the list, and then set the current user to the new first player in the list.

    评论

报告相同问题?

悬赏问题

  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line