1

I have a straight forward array with 8 values. I would like to turn it into an multidimensional array. Currently it looks like so:

array(8) {
  [0]=>
  int(0)
  [1]=>
  float(100)
  [2]=>
  int(0)
  [3]=>
  int(0)
  [4]=>
  float(0.5)
  [5]=>
  float(53.6)
  [6]=>
  float(32.8)
  [7]=>
  float(9.4)
}

Using the values above I would like the array to format like so:

array[0][0] = 0
array[0][1] = 100

array[1][0] = 0
array[1][1] = 0

array[2][0] = .5
array[2][1] = 53.6

etc.

So the goal is to create a loop that loops through and sets every 2 values to an array within an array. Any ideas?

1
  • have you ever used modulus(%) $x%2=??? Commented Jul 6, 2012 at 16:08

4 Answers 4

7

Use array_chunk to split the array every 2 elements.

This piece of code should give you exactly what you are looking for.

$newArray=array_chunk($oldArray,2,false);
Sign up to request clarification or add additional context in comments.

1 Comment

This was the way I finally have chosen as its less code and works very easily!
6

This should break out into the format you described.

$newArray = array();
for ($i=0;$i<count($originalArray);$i+=2) {
   $newArray[] = array($originalArray[$i], $originalArray[$i+1]);
}

1 Comment

Up voted the array_chunk answer. It is likely more performance friendly and at the very least, easier to read and understand.
2
$output = array();
for ($i = 0, $j = 0, $n = count($array); $i < $n; $i++) {
  $output[$j][] = $array[$i];
  if ($i % 2 == 1) {
    $j++;
  }
}

Or...

$output = array();
while ($array) {
  $output[] = array(array_shift($array), array_shift($array));
}

...and any number of variations on that theme.

Comments

1

Array transformation:

$a = array(0, 100, 0, 0, 0.5, 53.6, 32.8, 9.4);
$b = array();
$j=0;
foreach ($a as $i => $value) {
    if ($i%2) {
        $b[$j][1] = $value;
        $j++;
    } else {
        $b[$j][0] = $value;
    }
}
echo '<pre>';
var_export($a);
var_export($b);
echo '</pre>';

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.