# Meshing 2 arrays in PHP

• Beginner
• Posts: 48
• Loc: Reno, Nevada US

3+ Months Ago

I thought I'd throw this one out there and see what comes up.
Let's say I have 2 arrays. Array 1 has 28 entries and Array 2 has 7 entries. What I'd like to do is write some code that will evenly disperse the smaller array through the larger array. So, I guess output a third array with:

Array1[0]
Array1[1]
Array1[2]
Array1[3]
Array2[0]
Array1[4]
Array1[5]
Array1[6]
Array1[7]
Array2[1]
Array1[8]
... and so on.

It seems like it should be an easy thing to do, but I'm having major brainlock because it's so HOT in here. Anyone?
• Genius
• Posts: 13511
• Loc: Florida

3+ Months Ago

First thing to do is count both arrays.

Then, determine the point of insertion by seeing how many times the number of second array elements goes into the number of first arrays elements, floored.

Next, loop through the first array and check if

(\$i % \$insert_point == 0)

and insert an element from array2 any time that equates to zero.
• Beginner
• Posts: 48
• Loc: Reno, Nevada US

3+ Months Ago

That's exactly what I tried doing. I always ended up with either a blank entry or one missing from the end of the list. This is one of those "start over and think" types of problems. If only it wasn't so beastly hot in here...

Thanks joebert
• Genius
• Posts: 13511
• Loc: Florida

3+ Months Ago

Well, where's the code you started with ?

Maybe there's a rounding error, missing counter increment, or some other trivial thing to work out.
• Web Master
• Posts: 3243
• Loc: South Africa

3+ Months Ago

Also remember to deduct 1 from your total because arrays index from 0

I too would need a more verbose description as to what you are tyring to achieve because your example makes very little sense. What values does the array contain? Are you trying to merge the array or only display values inline with the length of the smaller array?
• Brewmaster
• Posts: 6302
• Loc: Seattle, WA

3+ Months Ago

Code: [ Select ]
\$step = count(\$arrayA) / count(\$arrayB);
\$result = array();
for( \$i = 0, \$j = 1; \$i < count(\$arrayA); ++\$i ) {
\$result[] = \$array[\$i];
if( \$i % \$step == 0 ) {
\$result[] = \$arrayB[\$j-1];
++\$j;
}
}
1. \$step = count(\$arrayA) / count(\$arrayB);
2. \$result = array();
3. for( \$i = 0, \$j = 1; \$i < count(\$arrayA); ++\$i ) {
4.     \$result[] = \$array[\$i];
5.     if( \$i % \$step == 0 ) {
6.         \$result[] = \$arrayB[\$j-1];
7.         ++\$j;
8.     }
9. }

Not perfect, but this is how I'd start approaching it.

## Post Information

• Total Posts in this topic: 6 posts
• Users browsing this forum: No registered users and 23 guests
• You cannot post new topics in this forum
• You cannot reply to topics in this forum
• You cannot edit your posts in this forum
• You cannot delete your posts in this forum
• You cannot post attachments in this forum

© 1998-2017. Ozzu® is a registered trademark of Unmelted, LLC.