PHP 从循环生成数组()?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5359082/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP Generate Array() from loop?
提问by kr1zmo
I just wrote this up, is this the most efficient way to add arrays to a preexisting array.
我刚刚写了这个,这是将数组添加到预先存在的数组的最有效方法。
$c=4;
$i=1;
$myarray = array();
while($i <= $c):
array_push($myarray, array('key' => 'value'));
$i++;
endwhile;
echo '<pre><code>';
var_dump($myarray);
echo '</code></pre>';
Update:How would you push the key & value, without creating a new array.
so this array_push($myarray,'key' => 'value');
not this array_push($myarray, array('key' => 'value'));
更新:如何在不创建新数组的情况下推送键和值。
所以这array_push($myarray,'key' => 'value');
不是这个array_push($myarray, array('key' => 'value'));
回答by markus
Your code has a couple of things which can be improved:
您的代码有一些可以改进的地方:
Magic Numbers
幻数
It's a bad practice to assign magic numbers like 4 and 1, use constants instead. For this example it's of course overkill but still important to know and use.
分配像 4 和 1 这样的幻数是一种不好的做法,而是使用常量。对于这个例子,它当然是矫枉过正,但了解和使用仍然很重要。
Lack of braces
缺少大括号
Always use the curly braces, it makes the code more readable.
始终使用大括号,它使代码更具可读性。
Wrong use of while loop
错误使用while循环
This is not a case for a while loop, if you want to loop a certain number of times, always use a for loop!
这不是while循环的情况,如果要循环一定次数,请始终使用for循环!
Unnessesary use of array_push
不必要地使用 array_push
You don't need array push to add elements to an array, you can and should probably use the shorthand function.
您不需要数组推送来向数组添加元素,您可以并且应该使用速记函数。
Result:
结果:
define('START', 1);
define('END', 4);
$myArray = array();
for ($i = START; $i < END; $i++)
{
$myArray[] = array('item' => '1 items');
}
回答by Prisoner
回答by NikiC
If you really need to only put a certain value n times into an array starting from a certain index, you could just use array_fill
:
如果您真的只需要将某个值 n 次放入从某个索引开始的数组中,您可以使用array_fill
:
$myarray = array_fill($i, $c, array('item' => '1 items'));
回答by mhitza
Your example looks fine to me, although you would most probably replace your array_push
function call with:
您的示例对我来说看起来不错,尽管您很可能会将array_push
函数调用替换为:
$myarray[] = array('item' => '1 items');
Which "is" a shorthand syntax for array_push.
其中“是”array_push 的简写语法。
Update:For an associative array you just do:
更新:对于关联数组,您只需执行以下操作:
$myarray["item"] = "1 items";
Although with your example you'll just overwrite the value on each iteration.
尽管在您的示例中,您只会覆盖每次迭代的值。
回答by omkar salunkhe
for($i=1; $i < 10; $i++) {
$option[$i] = $i;
}