【问题标题】:Fetch row and explode - PHP mySQL获取行并爆炸 - PHP mySQL
【发布时间】:2014-09-06 09:56:16
【问题描述】:

这是我的代码:

$postsql = "SELECT * FROM post WHERE id='{$_GET['id']}'";
$posts = mysqli_query($connect,$postsql) or die("Error: ".mysqli_error($connect));
$post = mysqli_fetch_array($posts);

$postAuthor = $post['author'];
$postDate = $post['date'];

$postCat = mysqli_fetch_row($post['cat']);// I've tags here separated by commas.
$postCatTag = explode(",",$postCat);

$postText = $post['text'];

echo "<img class='view_newsimg' src='{$postImg}'>
<h3 class='lath'>{$postTitle}</h3>
<ul class='det'><li class='adc'>avtori: {$postAuthor}</li>
<li class='adc'>TariRi: {$postDate}</li>
<li class='adc'>kategoria: <a href='#'>{$postCatTag}</a></li>"; // tags are shown here
echo <<<TEXT
<p class="news">{$postText}</p>
TEXT;

作为浏览器中标签部分的结果,它显示: 类别:数组 而不是显示表格中的标签。 为什么?怎样才能得到想要的结果?

【问题讨论】:

  • 如果要显示标签列表,请不要展开列表。
  • 但是标签不止一个,我希望它们有单独的链接。
  • 你应该使用循环。
  • 标签需要什么样的输出?
  • 我需要并排显示单独的链接

标签: php mysql row fetch explode


【解决方案1】:

$postCatTag 是一个数组。数组到字符串的转换总是产生Array。您可以使用implode-function 使用给定的分隔符来嵌入数组:

implode(', ', $postCatTag);

或者您可以只使用$postCat,因为它已经是一个字符串(标签由',' 分隔)。

【讨论】:

  • 我知道,请看我回答的最后一行。内爆部分是为了完整性,以防他想要自定义分隔符。
  • 如果变量中已经有逗号分隔的值而不是内爆需要什么?
  • 可能是因为tag1, tag2, tag3 看起来比tag1,tag2,tag3 好。我不建议使用与 explode 相同的分隔符再次内爆
  • 您的数据库是否还包括逗号后的空格?在这种情况下,只需将{$postCatTag} 替换为{$postCat}。否则使用...&lt;a href='#'&gt;" . implode(', ', $postCatTag) . "&lt;/a&gt;...
【解决方案2】:

$postCatTag 是一个数组。数组无法通过 echo 显示。

为此使用循环:

for($i=0;$i<count($postCatTag),$i++){

  echo "<li class='adc'>kategoria: <a href='#'>$postCatTag[$i]</a></li>";  

}

【讨论】:

  • 这个怎么插入?
  • 用我的代码替换 &lt;li class='adc'&gt;kategoria: &lt;a href='#'&gt;{$postCatTag}&lt;/a&gt;&lt;/li&gt;"; 检查并告诉我。
  • 我的代码中有一个小错误。我在答案中重新编辑了它。它的$i&lt;count($postCatTag) 不是$i&lt;=count($postCatTag)
  • 只是替换?像这样:echo "&lt;img class='view_newsimg' src='{$postImg}'&gt;&lt;h3 class='lath'&gt;{$postTitle}&lt;/h3&gt;&lt;ul class='det'&gt;&lt;li class='adc'&gt;avtori: {$postAuthor}&lt;/li&gt;&lt;li class='adc'&gt;TariRi: {$postDate}&lt;/li&gt; for($i=0;$i&lt;count($postCatTag),$i++){ echo "&lt;li class='adc'&gt;kategoria: &lt;a href='#'&gt;$postCatTag[$i]&lt;/a&gt;&lt;/li&gt;"; }"; 它什么都不显示/用 (') 替换 (") 并且结果是:&lt;li class='adc'&gt;TariRi: 2014-08-22 13:00:00&lt;/li&gt; for(=0;&lt;count(Array),++){ echo '&lt;li class='adc'&gt;kategoria: &lt;a href='#'&gt;&lt;/a&gt;&lt;/li&gt;'; }
  • 那是因为你的数组 $postCatTag 是空的。不要用 (') 替换 (")。编译器读取并转换 (") 内的所有内容,但是当它遇到 (') 时,它只会打印它。在某处写print_r($postCatTag) 并查看结果。它将显示数组内的内容。将帮助您调试代码。
【解决方案3】:
    echo "<li class='adc'>kategoria:'; 
    for($i=0;$i<count($postCatTag),$i++)
    {

              echo "<a href='#'>$postCatTag[$i]</a>";  

    }
    echo "</li>";

希望它对你有用。

【讨论】:

    猜你喜欢
    • 2010-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-26
    • 2013-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多