更好的 php array_merge

发布于 2024-09-17 17:30:42 字数 982 浏览 4 评论 0原文

我正在寻找一种更好的方法,而不需要对 $justPrices[$i] 的整数进行硬编码:

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

$justPrices 是一个多维数组,包含 4 个“bands”每个数组中的价格。例如,$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 循环,而且我仍然可以,我只是想知道是否有一个更好的方法,表面上看起来相对简单!

I am looking to do this a better way without the need to hardcode the integers for $justPrices[$i]:

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

$justPrices is a multidimensional array, containing 4 'bands' of prices within each array. The data for $justPrices being for example:

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 ) )

The issue is that the amount of arrays within $justPrices will vary from at least 2 to 10+. So I need a way for the parameters for the array_merge() function to vary dependent on the amount of arrays within $justPrices. I was going to use this simple method to get the amount of arrays within $justPrices:

$justPricesMax = count($justPrices);

I could write a for loop, and I might still, I just wondered if there was a better method for what seems on the surface relatively simple!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

是伱的 2024-09-24 17:30:42

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

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

这相当于函数调用:

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

If you just want to flatten the array, you can use call_user_func_array to call array_merge with the elements of $justPrices as parameters:

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

This is equivalent to a the function call:

$flat = array_merge($justPrices[0], $justPrices[1], … , $justPrices[count($justPrices)-1]);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文