首页 > 解决方案 > 为每个数组项添加 href

问题描述

我试图从数组项创建一个标签,数组项的数量总是不同的,

$myarray = 'sports,politics,entertainment,celebs';
$siteurl = 'http://example.com/';
$tag = explode(',', $myarray);

这就是我所做的

echo '<p>tag : <a href="'.$siteurl.'?'.$tag[0].'" >'.$tag[0].'</a>, 



<a href="'.$siteurl.'?'.$tag[1].'" >'.$tag[1].'</a>, 
<a href="'.$siteurl.'?'.$tag[2].'" >'.$tag[2].'</a>, 
<a href="'.$siteurl.'?'.$tag[3].'" >'.$tag[3].'</a>,
<a href="'.$siteurl.'?'.$tag[4].'" >'.$tag[4].'</a></p>';

我如何通过一次调用来回显此标签并获取所有数组项而不需要多少项编号?

编辑:$vatag 的错字

标签: phparrays

解决方案


您可以使用 foreach 循环来完成此操作,如下所示:

$myarray = 'sports,politics,entertainment,celebs';
$siteurl = 'http://example.com/';
$tag = explode(',', $myarray);

foreach($tag as &$value) {
    echo '<a href="'.$siteurl.'?'.$value.'" >'.$value.'</a>';
}

结果:

<a href="http://example.com/?sports" >sports</a><a href="http://example.com/?politics" >politics</a><a href="http://example.com/?entertainment" >entertainment</a><a href="http://example.com/?celebs" >celebs</a>

推荐阅读