kapoko
kapoko

Reputation: 988

Reorder PHP array by cycling through array in steps of (a number)

I have an array like this.

A note: in my case the strings are actually objects, but I replaced them with simple strings for the sake of the example.

$array = (
    0 => "pear basket 1", 
    1 => "apple basket 1", 
    2 => "orange basket 1",
    3 => "pear basket 2", 
    4 => "apple basket 2", 
    5 => "orange basket 2", 
    6 => "pear basket 3", 
    7 => "apple basket 3", 
    8 => "orange basket 3" 
);

I want to rearrange the array in such a way that it cycles through the old array in steps of n (3 in this case), so the order becomes: 0, 3, 6, 1, 4, 7, 2, 5, 8. The result would be:

$array = (
    0 => "pear basket 1", 
    3 => "pear basket 2", 
    6 => "pear basket 3",
    1 => "apple basket 1",
    4 => "apple basket 2", 
    7 => "apple basket 3", 
    2 => "orange basket 1",
    5 => "orange basket 2", 
    8 => "orange basket 3" 
);

I looked through all the PHP array functions but still don't know how to go about this.

Upvotes: 0

Views: 69

Answers (3)

Chris Lear
Chris Lear

Reputation: 6742

Here's a slightly different take

$array = array(
    0 => "pear basket 1",
    1 => "apple basket 1",
    2 => "orange basket 1",
    3 => "pear basket 2",
    4 => "apple basket 2",
    5 => "orange basket 2",
    6 => "pear basket 3",
    7 => "apple basket 3",
    8 => "orange basket 3"
);

$len=sizeof($array)-1;

$steps=3;
$new=$array;
foreach ($array as $k=>$v) {
    if ($k==$len) {
        break;
    }
    $newk=($k*$steps)%$len;
    $new[$newk]="$v";
}
ksort($new);

var_dump($new);

Upvotes: 0

Faito
Faito

Reputation: 833

Sometimes a man has to code what a framework does not offer, happy coding.

$array = array("pear basket 1", "apple basket 1", "orange basket 1", "pear basket 2", "apple basket 2", "orange basket 2", "pear basket 3", "apple basket 3", "orange basket 3" );

$newArray = array();


for ($i=0; $i < 3; $i++) { 
    for ($j=0; $j < 9; $j+=3) { 
        array_push($newArray, $array[($i+$j)]);
    }
}

Upvotes: 1

Barmar
Barmar

Reputation: 781833

There's no built-in functions that do this (why do people expect predefined functions that perform such ideosyncratic operations?). It's just a simple nested loop.

$steps = 3;
$new_array = array();
for ($i = 0; $i < $steps; $i++) {
    for ($j = $i; $j < count($array); $j += $steps) {
        $new_array[$j] = $array[$j];
    }
}

Upvotes: 1

Related Questions