梳理3阵列成一个阵列 [英] Combing 3 arrays into one array

查看:153
本文介绍了梳理3阵列成一个阵列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下阵列:

  $ =前阵列(front_first,front_second);
$里面=阵列(inside_first,inside_second,inside_third);
$背面=阵列(back_first,back_second,back_third,back_fourth);

我需要做的就是结合起来,使输出看起来像这样出现上述情况。输出顺序总是把他们为了后面,前面,在

  $最终=阵列(
back_first
front_first
inside_first
back_second
front_second
inside_second
back_third
front_second
inside_third
back_fourth
front_second
inside_third
);

所以基本上,它看起来在三个数组,数组取其少值,它会多次重复使用的最后一个值,直到它循环遍历数组更长的其余按键。

有没有办法做到这一点?我难倒/


解决方案

  $ =前阵列(front_first,front_second);
$里面=阵列(inside_first,inside_second,inside_third);
$背面=阵列(back_first,back_second,back_third,back_fourth);函数foo(){
  的$ args = func_get_args();
  $最大值= MAX(array_map('sizeof的',$参数)); //学分hakre;)
  $结果=阵列();  为($ I = 0; $ I< $最大; $ I + = 1){
    的foreach($ ARGS为$ ARG){
      $结果[] =使用isset($ ARG [$ i])? $ ARG [$ i]:结束($ ARG);
    }
  }  返回$结果;
}$最后= foo的($后面,前面的$,在$);
的print_r($决赛);

演示:的http://$c$cpad.viper-7.com/RFmGYW

I have the following 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");

what I need to do is combine it so that an output would look like this for the above situation. The output order is always to put them in order 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"
);

So basically it looks at the three arrays, and whichever array has less values it will reuse the last value multiple times until it loops through the remaining keys in the longer arrays.

Is there a way to do this? I am stumped/

解决方案

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

demo: http://codepad.viper-7.com/RFmGYW

这篇关于梳理3阵列成一个阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆