ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

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

2019-10-28 08:29:19  阅读:36  来源: 互联网

标签:concatenation arrays string 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

标签:concatenation,arrays,string,php
来源: https://codeday.me/bug/20191028/1951118.html

专注分享技术,共同学习,共同进步。侵权联系[admin#icode9.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有