混合多个php字符串

时间:2013-12-19 12:47:24

标签: php string

我正在尝试将四个字符串(用逗号分隔)的单词混合成一个字符串,如下所示:

$string1 = "apple, banana, grape";
$string2 = "red, yellow, black"; 
$string3 = "north, south, east"; 
$string4 = "april, may, june";  

$output_string = "apple, red, north, april, banana, yellow, south, may, grape, black, east, june";

关于如何做的任何想法?

4 个答案:

答案 0 :(得分:0)

我认为您可以使用以下代码。

 $totalString = implode(', ', array($string1, $string2, $string3, $string4));
 $splittedValues = explode ( ',', $totalString );

 // trim all values
 $result = array_map('trim', $splittedValues);

 // randomize all values
 $result = shuffle($result);

 // merge it to a string
 $output_string = implode(', ', $result);

古德勒克,

的Stefan

答案 1 :(得分:0)

试试这个(但这不是优化的好方法),如果元素的顺序很重要,请使用此

 $string1 = "apple, banana, grape";
    $string2 = "red, yellow, black"; 
    $string3 = "north, south, east"; 
    $string4 = "april, may, june";  

$piece1 = explode(",", $string1);
$piece2 = explode(",", $string2);
$piece3 = explode(",", $string3);
$piece4 = explode(",", $string4);


$i = 0;
foreach($piece1 as $element){
     $resultArray[] = $element;
     $resultArray[] = $piece2[$i];
     $resultArray[] = $piece3[$i];
     $resultArray[] = $piece4[$i];
     $i++;
}

var_dump(implode(",", $resultArray));

<强>结果:

字符串(75)“苹果,红色,北,四月,香蕉,黄色,南,五月,葡萄,黑色,东,六月”

<强>编辑。更短的方式:

$i = 0;
foreach($piece1 as $element){
     $resultArray.= $element.",".$piece2[$i].",".$piece3[$i].",".$piece4[$i];
     $i++;
}
var_dump( $resultArray);

结果将是相同的

答案 2 :(得分:0)

$string1 = "apple, banana, grape";
$string2 = "red, yellow, black"; 
$string3 = "north, south, east"; 
$string4 = "april, may, june";

$myArray = array(
    explode(',', $string1),
    explode(',', $string2),
    explode(',', $string3),
    explode(',', $string4),
);

$transposedData = call_user_func_array(
    'array_map',
    array_merge(
        array(NULL),
        $myArray
    )
);

array_walk(
    $transposedData,
    function(&$value) {
        $value = implode(', ', $value);
    }
);
echo implode(',', $transposedData);

答案 3 :(得分:0)

您可以创建接受多个字符串的功能,返回随机字符串:

function mix_multiple_strings() {
    $strings = array();
    foreach (func_get_args() as $string) {
        $strings = array_merge($strings, explode(', ', $string));
    }
    shuffle($strings);
    return implode(', ', $strings);
}

echo mix_multiple_strings($string1, $string2, $string3, $string4);

demo

或将在您的订单中排列字符串的功能:

function arrange_multiple_strings() {
    $strings = array();
    $n = func_num_args();
    foreach (func_get_args() as $i => $string) {
        foreach (explode(', ', $string) as $j => $val) {
            $strings[$n * $j + $i] = $val;
        }
    }
    ksort($strings);
    return implode(', ', $strings);
}

echo arrange_multiple_strings($string1, $string2, $string3, $string4);

demo