一个更好的PHP数组合并方法

6

我希望能找到一种更好的方法,而不需要硬编码整数 $justPrices[$i]

$pricesResult = array_merge($justPrices[0], $justPrices[1], $justPrices[2], $justPrices[3]);

$justPrices是一个多维数组,每个数组中包含4个价格“区间”。例如,$justPrices的数据如下:

Array ( [0] => Array ( [0] => 40.95 [1] => 39.95 [2] => 39.45 [3] => 38.95 ) [1] => Array ( [0] => 45.80 [1] => 41.80 [2] => 41.50 [3] => 41.40 ) [2] => Array ( [0] => 45.95 [1] => 42.95 [2] => 41.95 [3] => 41.45 ) [3] => Array ( [0] => 50.00 [1] => 50.00 [2] => 50.00 [3] => 50.00 ) )

问题在于$justPrices中的数组数量将至少从2个变化到10个以上。因此,我需要一种方法让array_merge()函数的参数根据$justPrices中的数组数量而变化。我打算使用这个简单的方法来获取$justPrices中的数组数量:
$justPricesMax = count($justPrices);

我可以写一个 for循环,我可能仍然会这样做,只是我想知道是否有更好的方法来处理表面上相对简单的事情!


@Gumbo 一个包含所有价格的单一数组。我之后会用它来计算平均价格。 - freeMagee
1个回答

11

如果您只想将数组展平,可以使用call_user_func_array调用$justPrices元素作为参数的array_merge

$flat = call_user_func_array('array_merge', $justPrices);

这相当于函数调用:

$flat = array_merge($justPrices[0], $justPrices[1], … , $justPrices[count($justPrices)-1]);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接