3

我有一个数组

$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但没有其他项目。那么我哪里错了?

4

5 回答 5

4

只需这样做:

$newvar = $variables_a;

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

$newvar 将包含您想要的数组

于 2012-11-01T10:27:44.083 回答
3

请循环遍历数组 c,如:

foreach($variables_b as $var) {
    $variables_c[$var] = $$var;
}
于 2012-11-01T10:21:42.627 回答
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"
于 2012-11-01T10:27:11.940 回答
2

尝试这个,

foreach($variables_b as $var) {
   $variables_c[$var] = $$var;
}
于 2012-11-01T10:22:55.383 回答
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);
于 2012-11-01T10:27:23.000 回答