virepo virepo - 2 months ago 9
PHP Question

Reverse every 4 items of an array in PHP

Sorry about the question title, I didn't know what to call it. So if anyone can update it to something more appropriate that would be great

I have a simple array that looks like this:

Array
(
[0] => Array
(
[id] => 8692
[name] => d
)

[1] => Array
(
[id] => 8691
[name] => c
)

[2] => Array
(
[id] => 8690
[name] => b
)

[3] => Array
(
[id] => 8689
[name] => a
)

[4] => Array
(
[id] => 8500
[name] => d
)

[5] => Array
(
[id] => 8499
[name] => c
)

[6] => Array
(
[id] => 8498
[name] => b
)

[7] => Array
(
[id] => 8497
[name] => a
)
)


This array is quite long so I only included the first 4 items to give you an idea.

My problem is that I need the array to be in a format of

a,b,c,d,a,b,c,d


At the minute the format is like:

d,c,b,a,d,c,b,a


By this I mean the ['name'] value which is either a,b,c or d.

So I every 4 items in the array need to be reversed.

I have tried to achieve this but fail every time ending up with lots of for & while loops.

Can anyone help me please?

Answer

You can do it using array_chunk, array_merge and array_reverse:

$finalArray = array();

$arrays = array_chunk($myArray, 4);

foreach ($arrays as $array) {
    $finalArray = array_merge($finalArray, array_reverse($array));
}