I have an array with numerical incrementing keys starting at 0
, like 0 1 2 3 4 5 ....etc
. I need to assign new keys to the array in the following manner
The first three keys keep their index number
Every 4th key gets incremented by 4
The two keys after the fourth gets incremented by 1
again
I know I need to use a foreach
loop ( seems the simplest way anyway ) to build a new array with newly assigned keys. My problem is the calculation of the keys
Here is my current array keys
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
and this is what I need them to be
0 1 2 6 7 8 12 13 14 18 19 20 24 25 26 30
Lets break this down into 3 key groups with the old array key on the top and the new array key at the bottom
1st group
0 1 2
0 1 2
2nd group
3 4 5
6 7 8
3rd group
6 7 8
12 13 14
4th group
9 10 11
18 19 20
etc etc......
When you look at the relationship between the two array keys, you'll see the following:
The old array keys 0
, 1
and 2
keep their key value
The old array keys 3
, 6
, 9
etc, if multiplied by 2
, gives you the new array key value
The old array keys 4
, 7
, 10
etc, if multiplied by 2
and you subtract 1
from that total, you get the new array key for that specific key
The old array keys 5
, 8
, 11
etc, if multiplied by 2
and you subtract 2
from the total, you get the new array key for that specific key
Alternatively, if you subtract the old key from the new key, you get the following answer
0
for the 1st group
3
for the 2nd group
6
for the 3rd group
9
for the 4th group
etc etc.....
The only solution I can think of is to use the modulus operator (inside my foreach
loop), check the current key against the modulus result and then calculate my new key
Example:
if ( $key%3 == 0 && $key != 0 ) {
$new_key = $key * 2;
} elseif ( ( $key - 1 ) %3 == 0 && $key != 1 ) {
$new_key = ( $key * 2 ) - 1;
} elseif ( ( $key - 2 ) %3 == 0 && $key != 2 ) {
$new_key = ( $key * 2 ) - 2;
} else {
$new_key = $key;
}
$new_array[$new_key] = $value;
Isn't there a smarter more mathematical way of doing this?
Try the following:
$new_key = floor($old_key / 3) * 3 + $old_key
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With