【问题标题】:PHP - Using a while loop to create a nested arrayPHP - 使用 while 循环创建嵌套数组
【发布时间】:2012-07-24 16:26:47
【问题描述】:

我想做一个这样的数组

$array = array("'firstName1', 'lastName1'", "'firstName2', 'lastName2'", ......);

我总是收到这样的错误:

解析错误:语法错误,意外的 'while' (T_WHILE),在第 11 行的 C:\wamp\www\Tests\index.php 中需要 ')'

<!doctype html>
<html>
<head>
    <meta charset="utf=8">
</head>
<body>
<?php
if(isset($_POST['reg'])){
    $x=1;
    $a = array(
    while($x<=10):
    "'firstName$x', 'lastName$x'"; //I DONT KNOW WHAT TO DO IN THIS LINE//
    $x++;
    endwhile;
    );
    print_r($a);
}
?>
<form action="" method="post">
<input type="text" name="number" /> <input type="submit" name="submit" value="Submit"/>
</form>
    <form action="" method="post">
    <table>
    <?php
    if(isset($_POST['submit'])){
    for($i=1;$i<=$_POST['number'];$i++){
    echo "<tr>
    <td><input type='text' name='firstName$i' /></td>
    <td><input type='text' name='lastName$i' /></td>
    </tr>";
    }
    $i-=1;
    echo "<input type='hidden' name='hide' value='$i' />";
    }           
    ?>
    </table>
    <input type="submit" value="Register" name="reg"/>
    </form>
</body>
</html>

【问题讨论】:

  • 感谢您检查我的错误! =)

标签: php arrays while-loop


【解决方案1】:
$a = array();

while($x<=10):
    $a[] = 'firstName'.$x;
    $a[] = 'lastName'.$x;
    $x++;
endwhile;

我再次阅读了你的问题,如果你希望这个 "'firstName1', 'lastName1'" 实际上是一个字符串,那么,

$a = array();
while($x<=10):
    $a[] = 'firstName'.$x.'lastName'.$x;
    $x++;
endwhile; 

或者根据你的问题标题(嵌套数组),

$x = 1;
while($x<=10):
   $a[] = array('firstName'.$x, 'lastName'.$x);
   $x++;
endwhile;

【讨论】:

  • 不需要先声明数组。您正在使用简短的语法来做到这一点。
  • 非常感谢..这正是我所需要的..但​​是如果我想让它像这样 $a[] = "'$_POST[firstName$x]', '$ _POST[姓氏$x]'";
    输出将是这样的 ('Kevin Steve', 'Maningo')
  • 使用这个 $a[] = $_POST["firstName".$x].", ".$_POST["lastName".$x];
  • 谢谢,已经完成了。我做了这样的$a[] = "'".$_POST["firstName".$x].", ".$_POST["lastName".$x]."'";,它也可以按我的意愿工作..谢谢
【解决方案2】:
if(isset($_POST['reg'])){
$x=1;
$a = array();
while($x<=10){
 $a[] = "firstName$x";
 $a[] = "lastName$x";
 $x++;
}

print_r($a);

}

【讨论】:

  • 我不确定使用双引号是否完全有资格获得重复的答案,因为变量扩展并没有改善串联。
  • @RobB,好吧,当我在提问者使用的单引号中使用变量时,我遇到了一些错误:),我认为最好使用双引号而不是单引号中的变量引号。
【解决方案3】:

希望对您有所帮助。

$x = 1;
while($x <=10 ):    
    $a[] = '"\'firstName'.$x.'\', \'lastName'.$x.'\'"';    
    $x++;
endwhile;
echo '<pre>';
print_r($a);
echo '</pre>';

输出是:

Array
(
    [0] => "'firstName1', 'lastName1'"
    [1] => "'firstName2', 'lastName2'"
    [2] => "'firstName3', 'lastName3'"
    [3] => "'firstName4', 'lastName4'"
    [4] => "'firstName5', 'lastName5'"
    [5] => "'firstName6', 'lastName6'"
    [6] => "'firstName7', 'lastName7'"
    [7] => "'firstName8', 'lastName8'"
    [8] => "'firstName9', 'lastName9'"
    [9] => "'firstName10', 'lastName10'"
)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-03-13
    • 2018-03-31
    • 1970-01-01
    • 1970-01-01
    • 2014-11-11
    • 2017-05-30
    • 1970-01-01
    相关资源
    最近更新 更多