PHP Split&将数组连接到单独的行

时间:2016-05-07 23:45:05

标签: php arrays string join split

我有以下数组:

Array ( [0] => Array ( [0] => Bob 
                       [1] => Freddy 
                     ) 
        [1] => Array ( [0] => IT Dev 
                       [1] => Programmer 
                     ) 
        [2] => Array ( [0] => 123 
                       [1] => 23423 
                     ) 
      )

我正在尝试将阵列连接在一起,所以它看起来如下所示:

Bob - IT Dev - 123

Freddy - 程序员 - 23423

我一直在搞乱内幕函数,但在所有现实中我都不知道如何在PHP中实现这一点

非常感谢任何帮助。

非常感谢

最高

4 个答案:

答案 0 :(得分:1)

如果你的数组被称为$myArray,那么:

foreach ($myArray as $row)
{
  $string1 .= $row[0]."-";
  $string2 .= $row[1]."-";
}

echo $string1."<br>";
echo $string2."<br>";

答案 1 :(得分:0)

让我们说这是你的阵列:

$array = array(
    array('Bob', 'Freddy'),
    array('IT Dev', 'Programmer'),
    array('123', '23423')
);

你必须循环遍历每个数组,将它们连接成一个句子。

$result = array();
foreach($array as $data){
    foreach($data as $index => $value){
        if(!isset($result[$index]))
            $result[$index] = $value;
        else
            $result[$index] .= " - " . $value;
    }
}

现在,如果您var_dump $result

array(2) {
    [0]=>
        string(18) "Bob - IT Dev - 123"
    [1]=>
        string(27) "Freddy - Programmer - 23423"
}

如果您想访问单个句子,可以执行以下操作:

echo $result[0]; // Bob - IT Dev - 123

答案 2 :(得分:0)

只需使用array_column和implode来获取输出。

<强>阵列:

$arr = array(
    array('Bob', 'Freddy'),
    array('IT Dev', 'Programmer'),
    array('123', '23423')
);

<强>机制

echo implode(" - ", array_column($arr, 0)); //Bob - IT Dev - 123
echo implode(" - ", array_column($arr, 1)); //Freddy - Programmer - 23423

答案 3 :(得分:0)

我有两种坚实的方法。第一种是&#34;可变方法&#34; (... splat operator),第二个是利用array_column()的经典foreach循环。

代码:(Demo

$array=[
    ['Bob','Freddy'],
    ['IT Dev','Programmer'],
    [123,23423]
];

// Use this to see that both methods are flexible and produce the same result,
// so long as all subarrays have equal length.
// If there are differences in length, depending where the hole is, the results
// between the two methods will vary slightly.
// (The 1st method best preserves the intended output structure.)
/*$array=[
    ['Bob','Freddy','Jane'],
    ['IT Dev','Programmer','Slacker'],
    [123,23423,0],
    ['more1','more2','more3']
];*/

// this one requires php5.6 or better
$imploded_columns=array_map(function(){return implode(' - ',func_get_args());},...$array);
var_export($imploded_columns);

echo "\n\n";
unset($imploded_columns);

// or you can go with a sub-php5.6 version:
foreach($array[0] as $k=>$v){
    $imploded_columns[]=implode(' - ',array_column($array,$k));
}
var_export($imploded_columns);

两种方法的输出:

// variadic method
array (
  0 => 'Bob - IT Dev - 123',
  1 => 'Freddy - Programmer - 23423',
)

// foreach method
array (
  0 => 'Bob - IT Dev - 123',
  1 => 'Freddy - Programmer - 23423',
)