You're close with the code you have posted, you are just calculating the value of $j
in the wrong way.
Using your own code, there are just 2 changes you need to make... See the comments below to see what needs to be changed:
$types = array(
"text" => 2,
"image" => 2,
"audio" => 2,
);
$jump = count($types);
$output = [];
$j = 0;
foreach ($types as $item => $num) {
for ($i=0; $i < $num; $i++) {
$pos = $j + ($i * $jump); // 1. multiple $i and $jump instead of adding them
$output[$pos] = $item;
}
$j++; // 2. increment $j by 1 instead of the value of $jump
}
print_r($output);
This outputs the following:
Array
(
[0] => text
[3] => text
[1] => image
[4] => image
[2] => audio
[5] => audio
)
As you can see, the array keys are correct, but they are added out of sequence. If you are iterating over the array with a numeric key (e.g. for ($i=0;$i<$size;$i++)
) this doesn't matter, but if you need the elements ordered by key, you can do this:
ksort($arr);
Result after sort:
Array
(
[0] => text
[1] => image
[2] => audio
[3] => text
[4] => image
[5] => audio
)
How this works:
You start with j as 0. Then for each "type" you add it into the array in position $j + ($i * $jump)
.
So for the first type, the position is calculated as 0+(0*3)
i.e. 0
and then 0+(1*3)
=3
i.e. 4th position which is after the first 3 elements from the $types
list.
Now you move on and increment $j++
i.e. $j
=1, and then loop does same thing except one position higher. (1+(0*3)
=1
and 1+(1*3)
=4
).
When $j
is 2, it does the same except one position higher again etc.
(Thanks to Hepson for spotting the earlier bug!)