[英]php implode issue
我有一個數組$ x = array(a,b,c); 數組的每個元素都是一個url。
有一個函數鏈接($ 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等。但是,如果我想要兩個URL之間的逗號“,”,那是什么。 在沒有逗號“”的情況下,如何獲得超鏈接?
期望的輸出將是
hyperlink1 , hyperlink2 etc // note comma ',' should not be part of the hyperlink
您可以使用array_map和implode函數來簡化此過程。
$urls = array('http://www.google.com/', 'http://www.stackoverflow.com/');
$links = array_map("link", $urls);
echo implode(', ', $links);
$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);
function convert($x){
for($i=0;$i<count($new);$i++){
echo link($new[$i]) . ($i<count($new)-1?", ":""); // converts the url to hyperlink
}
function convert($x){
return implode(',', array_map('link', explode(',',$x)));
}
function convert($x)
{
$string = '';
foreach($x as $element)
{
$string .= link($element).',';
}
$string = rtrim($string, ',');
echo $string;
}
這樣可以避免最后一個鏈接的末尾帶有逗號。 //回顯link1,link2,link3
$x = array('foo', 'bar', 'baz');
// then either:
$x = array_map('link', $x);
// or:
foreach ($x as &$value) {
$value = link($value);
}
echo join(', ', $x);
$output = '';
foreach (explode(',',$x) as $url)
$output .= link($url);
$output = substr($output,0,-1);
echo $output;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.