Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
922 views
in Technique[技术] by (71.8m points)

arrays - A better php array_merge

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...