将数据添加到数组/耦合数组中

时间:2013-08-13 02:01:47

标签: php arrays array-merge array-push

我有两个数组:

第一个:

$positions = array(0 => array(6.35,3.93), 1 => array(16.85,3.93),  2 => array(6.35,10.9),  3 => array(16.85,10.9), 4 => array(6.35,18.48),  5 => array(16.85,18.48),  6 =>a rray(6.35,25.45), 7 => array(16.85,25.45));

第二个:

   $coupons = Array ( [0] => NGP7xdaERK [1] => LntKT38dXj [2] => UBG2fplvnx [3] => ymMkO6EF16 [4] => zsZCasRWrj [5] => cl6UJ1a7VS [6] => lrjc5vnpl6 [7] => mExuzQBOLs ) ;

我想将这两个数组合并为:

array(0 => array(6.35,3.93, NGP7xdaERK ), 1 => array(16.85,3.93, LntKT38dXj ), ...

我对处理这样的数组并不熟悉,我听说过array_push和array_merge,我知道我必须使用foreach循环以避免添加键,但我不知道如何用这样的信息制作具体的东西^^

你能帮助我吗? :)

非常感谢:)

3 个答案:

答案 0 :(得分:2)

$newarray = array();
foreach ($positions as $k => $v) {
    array_push($v, $coupons[$k]);
    $newarray[] = $v;
}

答案 1 :(得分:2)

假设您的阵列长度始终相同。你可以用这个:

$positions = array(0 => array(6.35,3.93), 1 => array(16.85,3.93),  2 => array(6.35,10.9),  3 => array(16.85,10.9), 4 => array(6.35,18.48),  5 => array(16.85,18.48),  6 => array(6.35,25.45), 7 => array(16.85,25.45));

$coupons = array ( 0 => 'NGP7xdaERK', 1 => 'LntKT38dXj', 2 => 'UBG2fplvnx', 3 => 'ymMkO6EF16', 4 => 'zsZCasRWrj', 5 => 'cl6UJ1a7VS', 6 => 'lrjc5vnpl6', 7 => 'mExuzQBOLs' ) ;

$result = array();

foreach($positions as $i=>$pos ) {
    $result[$i] = array_merge($pos, (array)$coupons[$i]);
}

print_r($result);

结果:

Array
(
    [0] => Array
        (
            [0] => 6.35
            [1] => 3.93
            [2] => NGP7xdaERK
        )

    [1] => Array
        (
            [0] => 16.85
            [1] => 3.93
            [2] => LntKT38dXj
        )

    [2] => Array
        (
            [0] => 6.35
            [1] => 10.9
            [2] => UBG2fplvnx
        )

    [3] => Array
        (
            [0] => 16.85
            [1] => 10.9
            [2] => ymMkO6EF16
        )

    [4] => Array
        (
            [0] => 6.35
            [1] => 18.48
            [2] => zsZCasRWrj
        )

    [5] => Array
        (
            [0] => 16.85
            [1] => 18.48
            [2] => cl6UJ1a7VS
        )

    [6] => Array
        (
            [0] => 6.35
            [1] => 25.45
            [2] => lrjc5vnpl6
        )

    [7] => Array
        (
            [0] => 16.85
            [1] => 25.45
            [2] => mExuzQBOLs
        )

)

答案 2 :(得分:0)

$out = array();
foreach ($positions as $key => $value){
    $out[] = array_merge($value, array($coupons[$key]));
}
print_r($out);