php - 为每个数组项添加 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 的错字
解决方案
您可以使用 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>
推荐阅读
- axios - axios将参数传入后端(@RequestBody),结果参数为null
- python - PyTorch 中的损失函数,并非我所有的训练示例都具有相同的权重
- c# - WindowChrome 导致视图 ContentControl 绑定出现问题?
- javascript - 如何正确读取发送到后端的复杂对象
- python-3.x - 如何在没有订阅者的情况下发布
- json - 在jsonpath中转义正斜杠
- r - multipanelfigure 库生成具有多张图片的面板
- javascript - 在 Firebase Firestore 中请求数据时出现“Uncaught TypeError: can't convert undefined to object”错误
- django - 如何将图像显示到所需的产品类别?(如果有两个单独的模型(产品和图像))
- python - 如何在python中的字典中选择两个对象