如何使用在此循环中创建的变量填充循环中的数组(在 php 中)?
how to fill an array in a loop with variables which are created in this loop (in php)?
我想用变量在循环中生成或填充数组(php)。但是这些变量是写在这个循环里的。
举个例子:
$i = 1;
while(i<10){
$a = array("$i","$i","$i");
i++;
}
第二个和第三个i变量应该在下一段中添加。所以最后数组将包含从 0 到 10 的数字。我发现了一些带有 $$variables 的东西,但我不认为有一个有用的用法。
有什么可能的方法吗?谢谢:)
我认为你被困住了,你不知道如何向数组添加元素,这是非常基本的事情。
只需像这样在每次迭代中向数组添加一个元素:
$i = 0;
while($i < 10) { //If you want 0 - 10 including 10, just change '=' to '<='
$a[] = $i;
$i++; //Assuming, that the missing dollar signs are typos, since you already did it right once
}
在此处阅读有关数组的更多信息:http://php.net/manual/en/language.types.array.php
另一种方法是只使用 range():
$a=range(0,10);
我想用变量在循环中生成或填充数组(php)。但是这些变量是写在这个循环里的。
举个例子:
$i = 1;
while(i<10){
$a = array("$i","$i","$i");
i++;
}
第二个和第三个i变量应该在下一段中添加。所以最后数组将包含从 0 到 10 的数字。我发现了一些带有 $$variables 的东西,但我不认为有一个有用的用法。
有什么可能的方法吗?谢谢:)
我认为你被困住了,你不知道如何向数组添加元素,这是非常基本的事情。
只需像这样在每次迭代中向数组添加一个元素:
$i = 0;
while($i < 10) { //If you want 0 - 10 including 10, just change '=' to '<='
$a[] = $i;
$i++; //Assuming, that the missing dollar signs are typos, since you already did it right once
}
在此处阅读有关数组的更多信息:http://php.net/manual/en/language.types.array.php
另一种方法是只使用 range():
$a=range(0,10);