dongzaijiao4863
2012-10-13 12:55
浏览 388
已采纳

PHP - 解决方法数组的未定义索引

I'm trying to simply add +1 to an array like this

$game['teamA']['goals']++;

But then it'll throw me an error about undefined index. And I guess that's because $game['teamA']['goals'] is not set before I am adding a value to it.

But isn't there a way to workaround this?

I could set the $game['teamA']['goals'] = 0 in start of simulation, but then I have to do that with freekicks, penalties, cards etc., AND do it for both teams. Isn't there another way of doing this?

Thanks in advance :)

图片转代码服务由CSDN问答提供 功能建议

我试图简单地向这样的数组添加+1

  $ game ['teamA'] ['goals'] ++; 
   
 
 

但是它会给我一个关于未定义索引的错误。 我想那是因为 $ game ['teamA'] ['goals'] 在我添加值之前没有设置。

但是isn' 有办法解决这个问题吗?

我可以在模拟开始时设置 $ game ['teamA'] ['goals'] = 0 ,但是 然后我必须用freekicks,点球,牌等来做到这一点,并为两支球队做到这一点。 是不是有另一种方法呢?

提前致谢:)

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

4条回答 默认 最新

  • duanruinong0619 2012-10-13 13:01
    最佳回答

    You should ALWAYS initialise variables before they are used. One way to do this would be:

    $game = array('teamA' => 
                      array(
                          'goals' => 0,
                          'freekicks' => 0,
                          'penalties' => 0,
                          ....
                      ),
                  'teamB' =>
                      array(
                          'goals' => 0,
                          'freekicks' => 0,
                          'penalties' => 0,
                          ...
                      )
                  );
    
    评论
    解决 无用
    打赏 举报
查看更多回答(3条)

相关推荐 更多相似问题