在我的代码中,我需要制作虚拟数组的多个副本。该数组很简单,例如 $dummy = array('val'=> 0)
。我想制作该数组的 N 个副本,并将它们附加到具有类似结构的现有数组的末尾。显然,这可以通过 for 循环来完成,但为了可读性,我想知道是否有任何内置函数可以使其更加冗长。
这是我使用 for 循环想出的代码:
//example data, not real code
$existingArray = array([0] => array('val'=>2),[1] => array('val'=>3) );
$n = 2;
for($i=0;$i<$n;$i++) {
$dummy = array('val'=>0); //make a new array
$existingArray[] = $dummy; //add it to the end of $existingArray
}
重申一下,如果存在这样的函数,我想用函数重写它。类似的东西(显然这些不是真正的函数):
//make $n copies of the array
$newvals = clone(array('val'=>0), $n);
//tack the new arrays on the end of the existing array
append($newvals, $existingArray)
最佳答案
我认为您正在寻找 array_fill
:
array array_fill ( int $start_index , int $num , mixed $value )
Fills an array with
num
entries of the value of thevalue
parameter, keys starting at thestart_index
parameter.
所以:
$newElements = array_fill(0, $n, Array('val' => 0));
您仍然需要自己处理将 $newElements
附加到 $existingArray
的操作,可能使用 array_merge
:
array array_merge ( array $array1 [, array $... ] )
Merges the elements of one or more arrays together so that the values of one are appended to the end of the previous one. It returns the resulting array.
If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended.
Values in the input array with numeric keys will be renumbered with incrementing keys starting from zero in the result array.
所以:
$existingArray = array_merge($existingArray, $newElements);
这一切都有效,因为您的顶级数组是数字索引的。
关于PHP 用函数制作数组的 N 份副本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14963915/