簡體   English   中英

用PHP創建帶有變量的鏈接的逗號分隔列表

[英]Create comma separated list of links with variable in PHP

我有一個變量,它呈現用戶名列表。 現在,我需要為每個用戶名添加一個鏈接。 鏈接是通過固定的URL和用戶名作為變量構建的。

示例鏈接: https : //www.example.org/something?userid= $ username

$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>

如果您只想正確引用:

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);

對於可能面臨相同問題的人,有效的解決方案:

<?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 ", ";}
}?>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM