Search code examples
phparraysloopssequencealgebra

finding a specific formula to sort an array in PHP


I was wondering if there were any mathematicians who could help me solve the following problem:

I am trying to turn the sequence of numbers 012345678 into 036147258.

The purpose is to sort the indices of a PHP array where no standard sorting function is viable.

This is as far as I have got:

for($i=0; $i<count($arrayWithNineIndices); $i++)
{
    $j=($i%3)*3;
    echo $j;
    if($i%3===0) echo " <----";
    echo "<br />";
}

which outputs 036036036 vertically with markers on the zeros.

Ideally what I need is a mechanism to add one to the values that follow first marker, then two to the values that follow the second.

I have spent all morning trying, mainly with (j=0; j<3; j++) loops, but to no avail.


Solution

  • $result = array();
    
    for ($i = 0; $i < 3; $i++) {
      for ($j = $i; isset($array[$j]); $j += 3) {
        $result[] = $array[$j];
      }
    }
    
    print_r($result);
    

    See it working