PHP/MySQL-递增变量名称以循环获取数据 [英] PHP/MySQL - Incrementing variable name to loop for data

查看:140
本文介绍了PHP/MySQL-递增变量名称以循环获取数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的teams表中有名为player1player2player3 ... player12的行.在PHP脚本中,我将它们设置为变量($player1$player2 ...),并希望遍历它们以检查它们是否为NULL,以及是否不对其进行计数.

I have rows in my teams table named player1, player2, player3 ... player12. In PHP script i set them as variables ($player1,$player2...) and want to loop through them to check if they are NULL, and if they are not to count them.

如何在PHP中增加变量?我尝试这样做是这样的:

How may I increment a variable in PHP? I have tried doing it likes this:

<?
    $playerspicked = 0;
    for($i = 1; $i <= 12; $i++) {
        $playercheck = "$player"+$i;
        if($playercheck != 0) {
            $playerspicked++;
        }
    }
?>

但这是行不通的.

推荐答案

您可以使用变量名周围的复杂表达式(花括号{})来实现此目的.

You can do this with complex expressions (curly brackets {}) around a variable name.

if(empty(${"player$i"})) {
    //player$i is empty
}

复杂的表达式使您可以动态设置变量名.

complex expressions allow you to set variable names dynamically.

为了帮助您更好地了解这些工作原理,我将向您展示 您也可以像常规字符串连接一样使用这些

To help you better understand how these work, I will show you that you can also use these just like regular string concatenation like so

$variable = "many test";
echo "this is a test echo. {$variable}";

我通常使用它来根据其键为许多数组变量生成一个变量

I commonly use this for generating a variable for many array variables based on their key

$array = array("key1" => "value1", "key2" => "value2");
foreach($array as $key => $value) {
    ${$key} = $value;
}

上面的代码将创建2个变量$key1$key2,并为其关联适当的值.

The code above would create 2 variables, $key1 and $key2, with the appropriate value associated with them.

或者,我很确定您可以在变量的前面再添加一个$,但是我会说这很难阅读并弄清楚发生了什么.

Alternatively, I'm pretty sure you can just add another $ to the front of your variable, but I would say this is harder to read and figure out what's going on.

$playercheck = "player"+$i;  
if($$playercheck != 0) {
    $playerspicked++;
}

这篇关于PHP/MySQL-递增变量名称以循环获取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆