0

我有以下数组:

$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"
);

所以基本上它会查看三个数组,无论哪个数组的值较少,它将多次重用最后一个值,直到它循环遍历较长数组中的剩余键。

有没有办法做到这一点?我被难住了/

4

2 回答 2

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

于 2013-01-17T14:41:53.737 回答
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
)
于 2013-01-17T14:41:09.917 回答