Howdy,
I have an array list of values. Now, each value contains a list of numbers.
What I want to do is take each list of numbers within each value and just paste them into a new, single dimensional, array.
Does anyone know how I can do this without tons and tons of loops?
Flatten 2d array into 1d array
Page 1 of 15 Replies - 12182 Views - Last Post: 16 July 2007 - 08:02 AM
Replies To: Flatten 2d array into 1d array
#2
Re: Flatten 2d array into 1d array
Posted 06 July 2007 - 01:16 PM
$source = array(array(1,2,3),array(4,5,6),array(7,8,9));
$target = array();
foreach ($source as $list) {
$target = array_merge($target,$list);
}
Although if your arrays are quite large this may not be the most optimal way to do it. Using 2 nested loops isn't really such a bad solution, and it's a lot clearer what's going on:
foreach ($source as $list) {
foreach ($list as $value) {
$target[] = $value;
}
}
--serializer
This post has been edited by serializer: 06 July 2007 - 01:17 PM
#3
Re: Flatten 2d array into 1d array
Posted 06 July 2007 - 01:17 PM
just need one loop, and put it into a function, to return a 1d array. Simple.
#4
Re: Flatten 2d array into 1d array
Posted 07 July 2007 - 01:33 PM
Doh! Somehow I though I was in the PHP forum. Edit seems to be disabled for my previous post?
The loop you need would use the AddRange method of collection classes:
--serializer
The loop you need would use the AddRange method of collection classes:
List<int> target = new List<int>();
foreach (List<int> list in source) {
target.AddRange(list);
}
--serializer
#5
Re: Flatten 2d array into 1d array
Posted 09 July 2007 - 10:43 AM
is it a 2d jagged array or a 2d square array? if it's square, are there any empty spots that you have to filter out?
#6
Re: Flatten 2d array into 1d array
Posted 16 July 2007 - 08:02 AM
It is a 2d square array.
I have kinda gone back and forth between nested loops and alternatives. For the sake of readability I just ended up using nested loops. This call is only being performed once. I was afraid that I needed to call this loop once every 10ms, and that just would have been killer on my system.
Thanks so much for the help guys, great ideas. =)
I have kinda gone back and forth between nested loops and alternatives. For the sake of readability I just ended up using nested loops. This call is only being performed once. I was afraid that I needed to call this loop once every 10ms, and that just would have been killer on my system.
Thanks so much for the help guys, great ideas. =)
Page 1 of 1
|
|

New Topic/Question
Reply




MultiQuote





|