简体   繁体   English

array_merge没有按预期工作

[英]array_merge not working as expected

I have an double level array. 我有一个双级数组。 On the first level there are about 10 indexes. 在第一级有大约10个索引。 These contain each to a 275 element array which each contains a word. 它们包含275个元素数组,每个数组都包含一个单词。

Array
(
[0] => Array
    (
    [0] => Suspendisse
    [1] => Nam.
    [2] => Amet
    [3] => amet
    [4] => urna
    [5] => condimentum
    [6] => Vestibulum
    [7] => sem
    [8] => at
    [9] => Curabitur
    [10] => lorem
    .... to [275]
    )
[1] => Array
    (
    ... you get the idea
    )
... 10 elements total
)

Now, through circumstances, like an added image that takes up space, I sometimes need to recalculate the number of words that are remaining and redistribute the array that still remains. 现在,通过环境,比如占用空间的添加图像,我有时需要重新计算剩余的单词数量,并重新分配仍然保留的数组。

For that I have written the below function to make the remaining array one big long array of words, that I can array_chunk then to the right proportions. 为此,我编写了下面的函数,使剩下的数组成为一个很长的单词数组,然后我可以将array_chunk调整到正确的比例。 &$array is the reference to the "mother array", $memory is an array of words that are surplus, $index is where we are iterating through a for loop, $limit is "array" length for the 2nd level, in this case 275 &$ array是对“mother array”的引用,$ memory是一个多余的单词数组,$ index是我们迭代for循环的地方,$ limit是第二级的“数组”长度,在这里案例275

function redistribute(&$array,$memory,$index,$limit)
{
$ret[] = $array[0];
// skip past the current processed items
for($c=1;$c<$index;$c++)
    {
    $ret[] = $array[$c];
    }
// apply current item
$ret[] = $array[$index];

//join the rest into one big array off words;
$r2=$memory;
$length = count($array);
for($c=$index+1;$c<$length;++$c)
    {
    array_merge($r2,$array[$c]);
    print_r($r2);
    }
}

The question 这个问题

array_merge(arr1,arr2) doesn't seem to work. array_merge(arr1,arr2)似乎不起作用。

when executing 执行时

redistribute($splitupchunk,array('test','test2','test3','test4'),$i,275);

print_r($r2) just prints test numbers without the extra variables from $array[$c]. print_r($ r2)只打印测试数字而没有来自$ array [$ c]的额外变量。 How do I fix this? 我该如何解决?

I found the reason why it didn't work. 我找到了它无效的原因。 I assumed that array_merge worked by reference instead of by return. 我假设array_merge通过引用而不是返回工作。

By making the line 通过制作线

array_merge($r2,$array[$c]);

$r2 = array_merge($r2,$array[$c]);

It now works as expected. 它现在按预期工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM