PHP 用函数制作数组的 N 份副本

标签 php arrays multidimensional-array

在我的代码中,我需要制作虚拟数组的多个副本。该数组很简单,例如 $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 the value parameter, keys starting at the start_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/

相关文章:

php - Laravel - 批量分配异常错误

javascript - 关于函数中数组的控制台日志行为

javascript - 将对象属性转换为自己的对象可能吗?

c++ - 数组一直只返回最后一个元素。 [C/阿杜伊诺]

Java:在二维数组中搜索单词

java - 如何从两个数组列表中删除不常见的元素

arrays - 在通用和惯用的 Swift 中递归计算多维数组中的项目

php - mysql插入后如何最好地访问警报数据

php - 管理员批准后在日期之间显示图像

php - 在 Yajra 数据表中找不到 DT_Row_Index