問題描述
我正在尋找一種更好的方法,而無需對(duì) $justPrices[$i]
的整數(shù)進(jìn)行硬編碼:
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
是一個(gè)多維數(shù)組,每個(gè)數(shù)組中包含 4 個(gè)價(jià)格波段".$justPrices
的數(shù)據(jù)例如:
$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 ) )
問題在于 $justPrices
中的數(shù)組數(shù)量至少會(huì)從 2 到 10+ 不等.所以我需要一種方法讓 array_merge()
函數(shù)的參數(shù)根據(jù) $justPrices
中的數(shù)組數(shù)量而變化.我打算使用這個(gè)簡單的方法來獲取 $justPrices
中數(shù)組的數(shù)量:
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);
我可以寫一個(gè) for 循環(huán)
,我可能仍然如此,我只是想知道是否有更好的方法來處理表面上看起來相對(duì)簡單的事情!
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!
推薦答案
如果你只是想扁平化數(shù)組,可以使用 call_user_func_array
以$justPrices
的元素為參數(shù)調(diào)用array_merge
:
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);
這相當(dāng)于一個(gè)函數(shù)調(diào)用:
This is equivalent to a the function call:
$flat = array_merge($justPrices[0], $justPrices[1], … , $justPrices[count($justPrices)-1]);
這篇關(guān)于一個(gè)更好的 php array_merge的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!