二维数组用逗号分隔成字符串

时间:2012-12-06 13:15:29

标签: php arrays string type-conversion comma

我当前的php代码返回三个数组。我想将这三个数组转换为3个逗号分隔的字符串。

我的数组回声看起来像这样..

array (size=3)
     0 => 
    array (size=3)
      0 => string '1' (length=1)
      1 => string 'here' (length=4)
      2 => string 'Skincare composition against free radicals' (length=42)
  1 => 
    array (size=3)
      0 => string '2' (length=1)
      1 => string 'tere' (length=4)
      2 => string 'Compositions and methods for modification of skin lipid content' (length=63)
  2 => 
    array (size=3)
      0 => string '3' (length=1)
      1 => string 'fere' (length=4)
      2 => string 'Method and apparatus for acne treatment' (length=39) 

帮我一个简单的PHP代码片段,将一个数组转换为逗号分隔值。我将在循环中将我的三个数组转换为字符串..

4 个答案:

答案 0 :(得分:3)

如果您尝试将数组转换为逗号分隔字符串,请使用implode():

<?php
    $oldArray = array(array("red","green","blue"),array("Larry","Moe","Curly"),array("puppy dogs","rainbows","butterflies"));

    foreach($oldArray as $array){
        $newArray[] = implode(",",$array);
    }

    echo "<pre>";
    print_r($newArray);
    echo "</pre>";
?>

/*
Output:
Array
(
    [0] => red,green,blue
    [1] => Larry,Moe,Curly
    [2] => puppy dogs,rainbows,butterflies
)

*/

答案 1 :(得分:2)

这样做

$comma_separated = implode(",", $array);

答案 2 :(得分:2)

将数组命名为for example: $array1,然后使用foreach创建一个数组。从那里使用implode来制作一个字符串。 EG:

foreach ($array1 as $value1){
 foreach ($value1 as $value){
  $newString[]=$value;
 }
}
$string=implode(", ", $newString);
echo $string; //will echo comma separated string

答案 3 :(得分:1)

目前还不清楚你在问什么,但我假设你想要implode内部数组,最后得到一个由3个字符串组成的数组。如果我是对的,以下是诀窍:

$arr = array(
  array(1, 'badger', 'longer text about badger'), 
  array(2, 'ferret', 'longer text about ferret'), 
  array(3, 'hamster', 'longer text about hamster'), 
);

// This is the line you're interested in
$newArr = array_map(function($el) { return implode(', ', $el); }, $arr);

var_dump($newArr);

/** Gives output:
array(3) {
  [0]=>
  string(35) "1, badger, longer text about badger"
  [1]=>
  string(35) "2, ferret, longer text about ferret"
  [2]=>
  string(37) "3, hamster, longer text about hamster"
}
**/