【发布时间】:2014-01-09 22:42:08
【问题描述】:
我正在尝试组合两个从 MySQL 检索信息的变量。
有人建议我使用array_merge(),它似乎在大多数情况下都有效。从数据库返回所有结果后,我不断收到Warning: Illegal string offset。有趣的是,前 8 个(查询的 LIMIT 为 8)是错误清除的,在打印 8 个结果后,会出现一个带有该错误的巨大列表。
查询
articleClass.php
public function latestArticles()
{
$sth = $this->db->prepare("SELECT * FROM articles
WHERE article_uid = article_uid
ORDER BY article_uid DESC LIMIT 8");
$sth->execute();
$row = $sth->fetchAll();
return $row;
}
public function articleTags()
{
$sth = $this->db->prepare("SELECT a.*, b.*
FROM articles a, article_tags b
WHERE b.tag_id = a.article_uid
");
$sth->execute();
$row = $sth->fetchAll();
return $row;
}
打印代码
index.php
include 'libraries/articleClass/articleClass.php';
$articleClass = new articleClass();
$latestArticles = $articleClass->latestArticles();
$articleTags = $articleClass->articleTags();
foreach(array_merge($latestArticles, $articleTags) as $data)
{
$first_uid = $data['article_uid'];
$first_image = $data['article_image'];
$first_title = $data['article_title'];
$first_content = $data['article_content'];
$first_created = gmdate("d M Y", $data['article_created']);
$first_tags = $data['tag_name'];
echo '
<article>
<img src="path-to-image/'.$first_image.'"/>
<h1>'.$first_title.'</h1>
<p>'.$first_content.'</p>
<ul>
<li>'.$first_tags.'</li>
</ul>
</article>
';
}
一旦index.php 被加载,8 篇文章会按原样打印在页面上,但我得到了:
注意:未定义索引:第 74 行 /var/www/new-design/index.php 中的 tag_name
试验和(大部分)失败
如果我将公共函数 article_tags 更改为 Fetch 而不是 FetchAll 我会收到以下错误:
警告:array_merge():参数 #2 不是第 67 行 /var/www/new-design/index.php 中的数组
警告:在第 67 行的 /var/www/new-design/index.php 中为 foreach() 提供的参数无效
我无法弄清楚如何在这方面取得成功,任何线索都会很棒。我从早上就开始了!
更新
article_tags 表
+--------------------------------+
| tag_id | article_id | tag_name |
+--------------------------------+
| 1 | 8 | awesome |
| 2 | 8 | sweet |
| 3 | 8 | gross |
+--------------------------------+
只有一个article_id对应被调用的文章,但是这篇文章仍然收到未定义的索引:tag_name 当然因为在array_merge中它们根本没有被合并。
【问题讨论】:
-
其中一个原因可能是未引用的
WHERE article_uid = article_uid--- 你能试试WHERE article_uid = 'article_uid'或WHERE article_uid = '$article_uid'看看这是否与引号和/或$符号不同,因为您使用的是$first_uid = $data['article_uid']; -
我不认为
array_merge在这里做你想要的:假设$sth->db->fetchAll()返回一个带有数字键的数组,你的结果数组只是一个附加到另一个数组。您可能想发布print_r($latestArticles)和print_r($articleTags)的结果(如果需要,请缩短它,以便您的帖子保持可读性),以便我们可以向您展示实际结果是什么(您可以告诉我们它应该是什么)。 -
@Fred-ii- 感谢您的建议,但只要正确分配引号,引号就不会影响结果。
-
好的,谢谢。很高兴知道它得到了解决,干杯。 @AttisBarros