将使用循环创建的数组附加到另​​一个数组

时间:2012-11-01 10:18:40

标签: php arrays multidimensional-array

我有一个数组

$variables_a = array(
   'a' => $a,
   'b' => $b,
   'c' => $c
);

然后是另一个$variables_b = array('x','y','z'),我想像这样循环遍历B数组:

foreach($variables_b as $var) {
    $variables_c[] = array($var => $$var);
}

然后合并A& C与$variables_combined = array_merge($variables_A, $variables_C)

一起使用

我希望获得的输出是我print_r

时的输出
Array
(
     [a] => a
     [b] => b
     [c] => c
     [x] => x
     [y] => y
     [z] => z
)

但我得到的是

Array
(
     [a] => a
     [b] => b
     [c] => c
     [0] => Array
         (
            [x] => x
         )    
     [1] => Array
         (
            [y] => y
         )    
     [2] => Array
         (
            [z] => z
         )    
)

如果我将$feature_variables[] = array($feature => $$feature)更改为$feature_variables = array($feature => $$feature),我会

Array
(
     [a] => a
     [b] => b
     [c] => c
     [z] => z
)

即。来自$variables_b的最后一项,但没有其他项目。那么我哪里出错?

5 个答案:

答案 0 :(得分:4)

这样做:

$newvar = $variables_a;

foreach($variables_b as $var)
{
$newvar[$var] = $var;
}

$ newvar将包含您想要的数组

答案 1 :(得分:3)

请循环遍历数组c,如:

foreach($variables_b as $var) {
    $variables_c[$var] = $$var;
}

答案 2 :(得分:2)

试试这个,

foreach($variables_b as $var) {
   $variables_c[$var] = $$var;
}

答案 3 :(得分:2)

<?php

$variables_a = array(
   'a' ,
   'b' ,
   'c'
);

$variables_b = array('x','y','z');
 $variables_c=array();

foreach($variables_a as $var) {
    $variables_c[$var] =$var;

}

foreach($variables_b as $var) {
    $variables_c[$var] =$var;

}
print_r($variables_c);

?>
============
and test in : "http://codepad.org/1ICZxPIG"

答案 4 :(得分:1)

$variables_a = array(
    'a' => $a,
    'b' => $b,
    'c' => $c
);
$variables_b = array('x','y','z');

foreach($variables_b as $var) {
$variables_c[$var] = $$var;
}


$variables_combined = array_merge($variables_a, $variables_c);

echo "<pre>";print_r($variables_combined);