2011-02-24 34 views
1

我有一個數組$ x = array(a,b,c);數組中的每個元素都是一個url。php內爆問題

有一個函數鏈接($ x [$ i]),它將數組的每個元素轉換爲超鏈接。

function convert($x){ 
$new = explode(',',$x); 
for($i=0;$i<count($new);$i++){ 
    echo link($new[$i]); // converts the url to hyperlink 
} 

這將顯示輸出作爲URL1 URL2等,但WHT,如果我想的逗號「」 2個URL之間。我如何得到這個,沒有逗號','成爲超鏈接的一部分?

所需的輸出將

hyperlink1 , hyperlink2 etc // note comma ',' should not be part of the hyperlink 
+0

回波鏈路($新[$ I])。 「」; – dmcnelis 2011-02-24 22:54:45

+0

你想把'array(「a」,「b」,「c」)'轉換成'「a,b,c」'? – Dogbert 2011-02-24 22:55:13

+0

@dmcnelis:在每個值的末尾會附加','。我不想','在最後一個值之後。 – user550265 2011-02-24 22:57:27

回答

3

您可以使用array_map和爆功能,使這個容易。

$urls = array('http://www.google.com/', 'http://www.stackoverflow.com/'); 

$links = array_map("link", $urls); 
echo implode(', ', $links); 
+0

+1爲優雅 – Basic 2011-02-24 23:16:39

0
function convert($x) 
{ 
$string = ''; 

foreach($x as $element) 
{ 
    $string .= link($element).','; 
} 

$string = rtrim($string, ','); 

echo $string; 
} 

這避免了最後一個環節,在年底有一個逗號,只要你想。 //呼應鏈接1,鏈接2,LINK3

1
$x = array(
    'http://google.pl', 
    'http://yahoo.com', 
    'http://msn.com' 
); 

function convert($array){ 
    $res = array(); 
    foreach ($array as $url) { 
     $res[] = '<a href="' . $url . '">' . $url . '</a>'; 
    } 
    return implode(', ', $res); 
} 

echo convert($x); 
1
function convert($x){ 
for($i=0;$i<count($new);$i++){ 
    echo link($new[$i]) . ($i<count($new)-1?", ":""); // converts the url to hyperlink 
} 
0
$x = array('foo', 'bar', 'baz'); 

// then either: 
$x = array_map('link', $x); 

// or: 
foreach ($x as &$value) { 
    $value = link($value); 
} 

echo join(', ', $x); 
0
$output = ''; 
foreach (explode(',',$x) as $url) 
    $output .= link($url); 
$output = substr($output,0,-1); 
echo $output; 
1
function convert($x){ 
    return implode(',', array_map('link', explode(',',$x))); 
}