在PHP中组合变量

I have 2 variables which contain values. Here are the variables:

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

How can I combine both variables to get this?

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

Assuming you have two string and want a third string, not an associative array:

$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

Take a look at the array_combine function.

You could do something like this, assuming $a and $b are comma-delimited strings and not arrays. If they're already arrays, you can skip the explode step and just pass them directly to 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) );

The explode function turns the comma-delimited strings into arrays.

Then the array based on $a is used for the new array's keys while the array based on $b is used for the values.

Assuming the above variables are arrays, use array_combine.

If $a and $b are comma-delimited strings, then use explode first.

$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' ... )