如何将variable1的每个值与variable2的每个值连接起来

时间:2017-02-20 09:28:19

标签: php arrays string string-concatenation

//一个更简单的东西可以让我得到我需要的是: 如何将variable1的每个值与variable2的每个值连接起来

$Var1 = 'my1, my2, my3'; // here I have dozens of entries, they are    symbols
$Var2 = 'word1, word2, word3'; // here also dozens of entries, are words.

如何将变量的所有键放在另一个变量的键中?

$Values_that_I_needed = 'my1word1, my1word2, my1word3, my2word1, my2word2, my2word3, my3word1, my3word2, my3word3'; 

如何使用所有这些值构建此变量值,而无需键入所有内容!?

想象一下60 my1,my2 ......和130 word1,word2 ......的例子。这是我的情况! 在每个130字之前放入60my! //我需要连接变量/ join / join变量的每个值/键,以及另一个变量的所有值/键,以避免手工制作所有这些组合。并加入另一个变量。

3 个答案:

答案 0 :(得分:1)

使用explodetrim函数的解决方案:

$Var1 = 'my1, my2, my3'; // here I have dozens of entries, they are    symbols
$Var2 = 'word1, word2, word3';
$result = "";
$var2_list = explode(',', $Var2);

foreach (explode(',', $Var1) as $w1) {
    foreach ($var2_list as $w2) {
        $result .= trim($w1) . trim($w2). ', ';
    }
}
$result = trim($result, ', ');
print_r($result);

输出:

my1word1, my1word2, my1word3, my2word1, my2word2, my2word3, my3word1, my3word2, my3word3

答案 1 :(得分:0)

如果var1和var2具有相同的长度

,则下面的cod应该有效
<?php
$tab1=explode(',',$var1);
$tab2=explode(',',$var2);

$c=$count($tab1);
$output='';
for($i=0;$i<$c;$i++){
$output.=$tab1[$i].$tab2[$i].', ';
}
echo $output; 

答案 2 :(得分:0)

$Var1 = 'my1, my2, my3';
$Var2 = 'word1, word2, word3';

$Array1 = explode(", ",$Var1); // create array from $Var1
$Array2 = explode(", ",$Var2); // create array from $Var2

foreach($Array1 as $My){
    foreach($Array2 as $Word){
        $Result[] = $My.$Word; // Join Var1 & Var2
    }
}
$Values_that_I_needed = implode(", ", $Result); 
echo $Values_that_I_needed; // my1word1, my1word2, my1word3, my2word1, my2word2, my2word3, my3word1, my3word2, my3word3