将两个数组组合成一个字符串

时间:2018-09-06 17:12:19

标签: php arrays for-loop

我需要用[爱尔兰,匈牙利,丹麦]创建一个名为ar1[Dublin, Budapest, Copenhagen]的新数组,然后用包含来自( ar2数组,后跟相应的大写字母。使用格式countries

检查下面的代码,但我知道那是做那个事的另一种方法。循环,但有人可以解释我如何?

"country = capital,
 * country = capital..."

4 个答案:

答案 0 :(得分:2)

您应该使用foreachkey

$ar1 = ["Dublin", "Budapest", "Copenhagen"];
$ar2 = ["Ireland", "Hungary", "Denmark"];
$ANSWER = '';
foreach($ar1 as $key => $capital) {
    $ANSWER .= $ar2[$key] . ' = ' . $capital . ', ';
}
echo rtrim($ANSWER, ', ');

...,然后rtrim删除最后一个,

https://3v4l.org/f8PJN

答案 1 :(得分:1)

使用array_combine()

的另一种方法
<?php
$ar1 = ["Dublin", "Budapest", "Copenhagen"];
$ar2 = ["Ireland", "Hungary", "Denmark"];
$result = array_combine($ar2,$ar1);

$ANSWER = '';
$i = 0;
$comma = ', ';
$len = count($result);
foreach($result as $country => $capital) {
    if ($i == $len - 1){
        $comma='';
    }
    $ANSWER .= $country . ' = ' . $capital.$comma;
    $i++;
}

echo $ANSWER;

演示: https://3v4l.org/WGtJ3

使用array_map()

$ar1 = ["Dublin", "Budapest", "Copenhagen"];
$ar2 = ["Ireland", "Hungary", "Denmark"];
$input = array_combine($ar2,$ar1);
$output = implode(', ', array_map(
    function ($v, $k) { return sprintf("%s=%s", $k, $v); },
    $input,
    array_keys($input)
));

echo $output;

演示: https://3v4l.org/qps1G

答案 2 :(得分:0)

更快捷,更简单的方法:

$countries=["Ireland", "Hungary", "Denmark"];
 $capitals=["Dublin", "Budapest", "Copenhagen"];
 $string=implode(',',array_map(function($country,$capital){ return "$country=$capital";},$countries,$capitals));
 var_dump($string);

输出:

string(50) "Ireland=Dublin,Hungary=Budapest,Denmark=Copenhagen"

答案 3 :(得分:0)

如果您在单独的变量中有两个相关列表,则通常更容易先将它们转换为单个结构。在PHP中,您可以这样操作:

$transposed = array_map(null, $ar1, $ar2);

一旦将它们组合起来,生成所需的输出就会简单得多:

echo implode(', ', array_map(function($row) {
    return "{$row[1]} = {$row[0]}";
}, $transposed));
  

爱尔兰=匈牙利都柏林=丹麦布达佩斯=哥本哈根

请参见https://3v4l.org/LfvIY