繁体   English   中英

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

[英]Appending an array created with a loop to another 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的最后一项,但没有其他项。 那我哪里错了?

这样做:

$newvar = $variables_a;

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

$ newvar将包含您想要的数组

请循环遍历数组c,如:

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

尝试这个,

foreach($variables_b as $var) {
   $variables_c[$var] = $$var;
}
<?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"
$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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM