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

したがって、基本的には 3 つの配列を調べ、値が少ない方の配列は、長い方の配列の残りのキーをループするまで、最後の値を複数回再利用します。

これを行う方法はありますか?私は困惑しています/

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 に答える