gpt4 book ai didi

PHP用函数制作N个数组副本

转载 作者:行者123 更新时间:2023-12-02 22:12:49 24 4
gpt4 key购买 nike

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com