2012-12-06 56 views
-2

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

我的阵列回声看起来是这样的..

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代码片段一个数组转换为逗号分隔值。我将在环路我的三个阵列转移到字符串工作..

+0

['join' ](http://php.net/join) – deceze

+0

@deceze但是'implode'更加戏剧化! – Leigh

+0

@Leigh我宁愿喜欢所有字符串以“加入”和谐......! :3 – deceze

回答

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 
+0

谢谢这对我有用 –

2

这将做

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

你是否尝试过内爆多维数组? – RobMasters

+0

@RobMasters他指定他只需要帮助转换一个阵列,他将在其他工作 – knightrider

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" 
} 
**/ 
3

如果你试图把一个数组转换成一个逗号分隔的字符串,使用破灭():

<?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 
) 

*/ 
相关问题