如何在PHP中将两个特定的数组键和值组合在一起?

时间:2012-06-13 22:59:27

标签: php arrays merge

我有两个有趣的阵列,我试图结合在一起。简单说一下:

$firstArr

array(3) {
  [0] => array(2) {
    [0] => string(1) "1"
    [1] => string(16) "test1"
  }
  [1] => array(2) {
    [0] => string(1) "8"
    [1] => string(26) "test2"
  }
  [2] => array(2) {
    [0] => string(1) "9"
    [1] => string(23) "test3"
  }
}


$secondArr

array(3) {
  [0] => string(1) "1"
  [1] => string(1) "2"
  [2] => string(1) "3"
}

我想得的是这样的(不是数组):

$x = 1, 8, 8, 9, 9, 9;
$y = test1, test2, test2, test3, test3, test3;

基本上第二个数组值决定了第一个数组值重复的次数。

任何想法?

1 个答案:

答案 0 :(得分:0)

$firstArr=array(array("1","test1"),array("8","test2"),array("9","test3"));


$secondArr=array("1","2","3");


$x=$y='';
foreach ($secondArr as $k=>$v){
$x.= str_repeat($firstArr[$k][0].',',$v);
$y.= str_repeat($firstArr[$k][1].',',$v);
}

echo rtrim($x,",").";\n";
echo rtrim($y,",").";";

输出:

1,8,8,9,9,9;
TEST1,TEST2,TEST2,TEST3,TEST3,TEST3;

工作演示:

http://codepad.org/yFvWs0Rh