【问题标题】:Create comma separated list of links with variable in PHP在 PHP 中使用变量创建逗号分隔的链接列表
【发布时间】:2018-11-22 07:31:12
【问题描述】:

我有一个呈现用户名列表的变量。现在,我需要为每个用户名添加一个链接。该链接由一个固定的 URL 和作为变量的用户名构建。

示例链接: https://www.example.org/something?userid=$用户名

$usernames = $_POST['username'];
$username = '';
foreach($usernames as $value) {
$username .= "'" . $value . "', ";
}
$username = rtrim($username, ', ');

然后,我构建了列表:

<?php  $urls = explode(',', $usernameid);
$nritems = count ($urls); 
$positem = 0;
foreach($urls as $key => $usernameid)
{
echo "<a href="https://www.example.org/something?userid=' . $usernameid . 
'">'. $usernameid . '</a>";
if (++$positem != $nritems) { echo ", ";}
}?>

该变量在代码的其他部分也有使用,所以我无法更改。该列表现在不显示。

感谢任何帮助。

更新:表格:

<form action="list.php" method="post" autocomplete="off">
  <div id="usrselect">
    <label>Select user <input type="text" name="username[]" id="userid" class="typeahead" required/></label>
   </div>
   <div class="button-section"> <input type="submit" name="List" /></div>
</form>

【问题讨论】:

  • 一点帮助https://www.example.org/something?userid=1 将产生$_POST['userid'],其中$_POST['userid'] 将等于1。 $_POST['username'] 甚至都不存在。 $_POST['userid'] 也不是一个数组,你不能在 foreach 中使用它。它会发出警告。
  • $POST 用于从表单的输入字段中“捕获”用户名。在代码中按原样使用它确实按预期工作。它返回用户名或用户名列表(如果在表单中选择了更多)。我无法解决的是为该列表中的每个用户名创建链接。
  • 注意echo 行中的引用,"&lt;a href=" 不起作用,以及 . '&lt;/a&gt;";
  • @SCor,好吧,缺少表单的代码部分。所以我基于现有代码的假设。还添加到引号部分 - 你到底在哪里得到$usernameid?据我所知,它是未定义的。
  • @EugeneAnisiutkin:你是对的。这是缺少的部分(表单)>

标签: php list hyperlink


【解决方案1】:

如果您只想正确引用:

echo '<a href="https://www.example.org/something?userid='.$usernameid.'">'.$usernameid.'</a>';

echo "<a href=\"https://www.example.org/something?userid={$usernameid}\">{$usernameid}</a>";

echo sprintf('<a href="https://www.example.org/something?userid=%d">%d</a>', $usernameid, $usernameid);

【讨论】:

  • 遗憾的是,这些都不起作用。在上一个版本中,有一个引号需要更改。 之后的 " 应该是 '
  • 这些是有效的例子并产生正确的代码,如果某些东西“不起作用”,它与$usernameid有关。我修复了',谢谢。
  • 变量实际上包含正确的$usernameid(而不是$username)
  • 那么到底是什么不起作用呢?错误的网址?身份证错了?您的日志文件或屏幕上是否有任何错误?此代码是否生成正确的链接代码,还是代码中其他地方的错误?
【解决方案2】:

适用于可能面临同样问题的人的有效解决方案:

<?php $urls = explode(',', $usernameid);
$nritems = count ($urls); 
$positem = 0;
$displayuser = array("'", " ");
foreach($urls as $key => $usernameid)
{
echo '<a href="http://www.example.com/something?userId='.str_replace($displayuser, "", $usernameid).'">'.str_replace($displayuser, "", $usernameid).'</a>';
if (++$positem != $nritems) { echo ", ";}
}?>

【讨论】:

    猜你喜欢
    • 2012-03-03
    • 1970-01-01
    • 2013-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-26
    • 1970-01-01
    • 2015-02-26
    相关资源
    最近更新 更多