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

我有三个这样的数组:

$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, ",");
}

解决方法:

这应该为您工作:

只需使用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
上一篇:c-通过串联另一个char *来初始化const char *


下一篇:python-熊猫系列中列表的有效串联