2012-01-19 45 views
-2

我有2个包含值的变量。这里是变量:在PHP中组合变量

$a = "1a, 2a, 3a, 3a_oth, 4a, 4a_oth"; 
$b = "1, 1, 8, Port, 10, UNIX"; 

我怎样才能结合这两个变量来得到这个?

$c = array('1a'=>'1', '2a'=>'1', '3a'=>'8', '3a_oth'=>'Port', '4a'=>'10', '4a_oth'=>'UNIX'); 
+0

$ a和$ b是像字符串:'$一个=“1A,2A,3A,3a_oth ,4a,4a_oth,';' – 2012-01-19 01:14:27

+0

$ c ['1a'] ='1';等等 – CountMurphy 2012-01-19 01:14:34

+2

这不是有效的代码,但你看看它。你能否提供实际样品或清理你的问题?你在谈论*组合数组*吗? (提示提示,搜索这些关键字!) – deceze 2012-01-19 01:15:07

回答

1

假设有两个串并希望第三个字符串,而不是关联数组:

$a = '1a, 2a, 3a, 3a_oth, 4a, 4a_oth'; 
$b = '1, 1, 8, Port, 10, UNIX'; 

function combine($a,$b){ 
    $c=''; 
    $aa = preg_split('/, /',$a); 
    $bb = preg_split('/, /',$b); 
    if(count($aa)!=count($bb))return false; 
    for($i=0;$i<count($aa);$i++){ 
     $c.=$aa[$i].'='.$bb[$i]; 
     if($i!=count($aa)-1)$c.=', '; 
    } 
    return $c; 
} 
echo combine($a,$b); // returns 1a=1, 2a=1, 3a=8, 3a_oth=Port, 4a=10, 4a_oth=UNIX 
4

看看array_combine函数。

你可以这样做,假设$a$b是逗号分隔的字符串而不是数组。如果它们已经是数组,则可以跳过explode步骤,直接将它们传递给array_combine

$a = "1a, 2a, 3a, 3a_oth, 4a, 4a_oth"; 
$b = "1, 1, 8, Port, 10, UNIX"; 

$c = array_combine(explode(",", $a), explode(",",$b)); 

explode函数将逗号分隔的字符串转换为数组。

然后,基于$a的数组用于新数组的键,而基于$b的数组用于该值。

3

假设上述变量是数组,请使用array_combine

如果$a$b是以逗号分隔的字符串,则首先使用explode

$a = explode("," $a); // only if $a is a string 
$b = explode("," $b); // only if $b is a string 

$a = array('1a', '2a', '3a', '3a_oth', '4a', '4a_oth'); // keys 
$b = array('1', '1', '8', 'Port', '10', 'UNIX');  // values 

$c = array_combine($a, $b); 
// outputs array('1a' => '1', '2a' => '1', '3a' => '8' ...)