将3个阵列组合成一个阵列

时间:2013-01-17 14:23:22

标签: php arrays

我有以下阵列:

$front = array("front_first","front_second");
$inside = array("inside_first", "inside_second", "inside_third");
$back = array("back_first", "back_second", "back_third","back_fourth");

我需要做的是将它组合起来,以便在上述情况下输出看起来像这样。输出顺序始终是按顺序back, front, inside

$final = array(
"back_first",
"front_first",
"inside_first",
"back_second",
"front_second",
"inside_second",
"back_third",
"front_second",
"inside_third",
"back_fourth",
"front_second",
"inside_third"
);

所以基本上它会查看三个数组,并且无论哪个数组具有较少的值,它都会多次重复使用最后一个值,直到它遍历较长数组中的其余键为止。

有办法做到这一点吗?我很难过/

2 个答案:

答案 0 :(得分:3)

$front = array("front_first","front_second");
$inside = array("inside_first", "inside_second", "inside_third");
$back = array("back_first", "back_second", "back_third","back_fourth");

function foo() {
  $args = func_get_args();
  $max = max(array_map('sizeof', $args)); // credits to hakre ;)
  $result = array();

  for ($i = 0; $i < $max; $i += 1) {
    foreach ($args as $arg) {
      $result[] = isset($arg[$i]) ? $arg[$i] : end($arg); 
    }    
  }

  return $result;
}

$final = foo($back, $front, $inside);
print_r($final);

演示:http://codepad.viper-7.com/RFmGYW

答案 1 :(得分:2)

演示

http://codepad.viper-7.com/xpwGha

PHP

$front = array("front_first", "front_second");
$inside = array("inside_first", "inside_second", "inside_third");
$back = array("back_first", "back_second", "back_third", "back_fourth");

$combined = array_map("callback", $back, $front, $inside);

$lastf = "";
$lasti = "";
$lastb = "";

function callback($arrb, $arrf, $arri) {
    global $lastf, $lasti, $lastb;

    $lastf = isset($arrf) ? $arrf : $lastf;
    $lasti = isset($arri) ? $arri : $lasti;
    $lastb = isset($arrb) ? $arrb : $lastb;

    return array($lastb, $lastf, $lasti);
}

$final = array();

foreach ($combined as $k => $v) {
    $final = array_merge($final, $v);
}

print_r($final);

输出

Array
(
    [0] => back_first
    [1] => front_first
    [2] => inside_first
    [3] => back_second
    [4] => front_second
    [5] => inside_second
    [6] => back_third
    [7] => front_second
    [8] => inside_third
    [9] => back_fourth
    [10] => front_second
    [11] => inside_third
)