如何将多个数组转换为单个变量字符串?

时间:2015-05-31 18:08:43

标签: php arrays string concatenation

我有三个这样的阵列:

$a = ["a1", "a2", "a3", "a4", "a5"];
$b = ["b1", "b2", "b3", "b4", "b5"];
$c = ["c1", "c2", "c3", "c4", "c5"];

我正在寻找一种方法将三个数组转换为单个字符串并将其保存在这样的变量中:

$abc = "a1 , b1, c1, a2, b2, c2, a3, b3, c3, a4, b4, c4, a5, b5, c5";

我尝试过爆炸,但也许我的方法不太好。我使用的是PHP 5.4。

注意

请注意,可以使用以下代码,但我不愿意使用它。 它适合我,但我想重新发明轮子:

array_push($abc, $a);
array_push($abc, ",");
array_push($abc, $b);
array_push($abc, ",");
array_push($abc, $c);

if ($key < (sizeof($a)-1)){
    array_push($abc, ",");
}

1 个答案:

答案 0 :(得分:4)

这应该适合你:

使用array_map()一次循环遍历所有3个数组。首先,您将数组转换为以下格式:

Array
(
    [0] => a1, b1, c1
    [1] => a2, b2, c2
    [2] => a3, b3, c3
    [3] => a4, b4, c4
    [4] => a5, b5, c5
)

然后你将implode()这个数组放入你期望的字符串中。

代码:

<?php

    $a = ["a1", "a2", "a3", "a4", "a5"];
    $b = ["b1", "b2", "b3", "b4", "b5"];
    $c = ["c1", "c2", "c3", "c4", "c5"];

    $result = implode(", ", array_map(function($v1, $v2, $v3){
        return "$v1, $v2, $v3";
    }, $a, $b, $c));

    echo $result;

?>

输出:

a1, b1, c1, a2, b2, c2, a3, b3, c3, a4, b4, c4, a5, b5, c5