【问题标题】:A better php array_merge一个更好的 php array_merge
【发布时间】:2011-04-07 18:33:45
【问题描述】:

我正在寻找一种更好的方法,而无需为$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 loop,我仍然可以,我只是想知道是否有更好的方法来处理表面上看起来相对简单的事情!

【问题讨论】:

  • @Gumbo 包含所有价格的单个数组。之后我将其用于平均价格。

标签: php arrays multidimensional-array array-merge


【解决方案1】:

如果只是想展平数组,可以使用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]);

【讨论】:

  • 字面意思就是这样。很棒的反应。
猜你喜欢
  • 1970-01-01
  • 2012-07-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-06
  • 1970-01-01
  • 2011-08-21
  • 2011-07-11
相关资源
最近更新 更多