2012-12-06 87 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 
) 

*/ 
相關問題