-2

just curious if someone knows how to merge every other sub array,

aka

$tmp = array();

$tmp[0] = array(false);
$tmp[1] = array(false);

$tmp[2] = array(false);
$tmp[3] = array(false);

$tmp[4] = array(false);
$tmp[5] = array(false);

or .... 0+1 2+3 4+5

something like this i think?

$i=0; $new=array();
foreach($tmp as $k=>$v) {
  $tmp[$k] = $v;
  if($i=$k-1) { 
    $new[] = $tmp[$i] + $tmp[$i-1]; /* or something ridiculous like that */
  }
  $i++;
} 
Book Of Zeus
  • 49,509
  • 18
  • 174
  • 171
ehime
  • 8,025
  • 14
  • 51
  • 110
  • What exactly was the point of editing this AND downvoting it, especially after it's been solved and accepted. Ridiculous.... – ehime Nov 09 '11 at 17:27

3 Answers3

2
$new = array();
for ($i = 0, $cnt = count($tmp); $i < $cnt; $i += 2) {
    $new[] = $tmp[$i] + $tmp[$i + 1];
}
zerkms
  • 249,484
  • 69
  • 436
  • 539
  • An array with an odd number of entries causes this to fail with "Notice: Undefined offset:" and "Fatal error: Unsupported operand types", as I noted below. – nickb Nov 08 '11 at 00:51
  • @nickb: indeed, but I didn't have a goal to do the all @ehime's work, but gave him an idea of how to write the base. Btw, it will fail in the case when `$tmp[$i]` is not an array, but an object, and I don't handle that, because it's out of the question scope. – zerkms Nov 08 '11 at 00:56
  • there's always an even number and in the case its an object you can always use string casting $mp = (array)$tmp; so its a non-issue. – ehime Nov 08 '11 at 17:36
1

Using array_chunk and array_merge you can come up with a fairly simple solution

<?php

$result = array_chunk($tmp, 2);

foreach ($result as &$chunk)
{
    $chunk = array_merge($chunk[0], $chunk[1]);
}
adlawson
  • 6,303
  • 1
  • 35
  • 46
  • 1
    In case a chunk has more than two elements, `call_user_func_array('array_merge', $chunk)` works as well. – Felix Kling Nov 08 '11 at 00:41
  • Ooh! Even better. Thanks for the input. – adlawson Nov 08 '11 at 00:42
  • 1
    even though this looks tricky and "nice" - I would never write such not obvious code in production (yes, for me it looks a little difficult to read and understand) – zerkms Nov 08 '11 at 00:42
0

This assumes that the array contains an even number of entries. If this is not the case, or if you're looking to merge 0 + 1, 1 + 2, 2 + 3, change the increment on $i to 1, and change the assignment of $j to $j = count( $tmp) - 1

$tmp = array();

$tmp[0] = array(false);
$tmp[1] = array(false);

$tmp[2] = array(true);
$tmp[3] = array(true);

$new = array();
for( $i = 0, $j = count( $tmp); $i < $j; $i += 2)
{
    $new[] = array_merge( $tmp[$i], $tmp[$i+1]);
}

Output

array(2) {
  [0]=>
  array(2) {
    [0]=>
    bool(false)
    [1]=>
    bool(false)
  }
  [1]=>
  array(2) {
    [0]=>
    bool(true)
    [1]=>
    bool(true)
  }
}
nickb
  • 59,313
  • 13
  • 108
  • 143