Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

php - How to merge a multidimensional array into one single dimension array

I have a multi dimension array that I want to merge all the inside arrays into one singer dimension array, I have tried array_merge with foreach but it doesn't help.

Example Array:

$nums = array (
  array(1,2,3),
  array(4,5,6),
  array(7,8,9)
);

What I did but get an empty array

$newArr = [];
foreach ($nums as $value) {
   array_merge($newArr, $value);
}

Expectation

$newArr = array(1,2,3,4,5,6,7,8,9)
question from:https://stackoverflow.com/questions/65836049/how-to-merge-a-multidimensional-array-into-one-single-dimension-array

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

1 Answer

0 votes
by (71.8m points)

You could use the function array_merge() this way :

$newArr = array_merge(...$nums)

It would make your code lighter and avoid the use of a foreach loop.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...