我有一些SQL执行bog标准搜索,然后在控制器(INDEX.PHP)中将这些结果存储到数组中。提取物如下所示:
INDEX.PHP Extract
foreach ($s as $row)
{
$results[] = array(
'id' => $row['id'],
'name' => $row['name'],
'gender' => $row['gender'],
'county' => $row['county'],
'constituency' => $row['constituency'],
'qualifications' => $row['qualifications'],
'bio' => $row['bio'],
'monday' => $row['monday'],
'tuesday' => $row['tuesday'],
'wednesday' => $row['wednesday'],
'thursday' => $row['thursday'],
'friday' => $row['friday'],
'saturday' => $row['saturday'],
'sunday' => $row['sunday'],
'filename' => $row['filename'],
'mimetype' => $row['mimetype']
);
}
include 'profiles-small.html.php';
exit();
然后在'profiles.html.php'页面中,我使用foreach循环输出我的结果,如下所示:
PROFILES-SMALL.PHP提取
<?php if (isset($results)): ?>
<?php foreach ($results as $result): ?>
<h1 class="margin-top">Search Results for <span class="red"><?php htmlout($result['constituency']); ?></span></h1>
<ol class="small-profile">
<img class="small-img" src="<?php if (!empty($result['filename'])) echo('?action=view&id=' . $result['id']); else echo "/img/profile_coming_soon.jpg" ?>" width="100" height="100" />
<li><?php htmlout($result['name']); ?></li>
<!--<li class="list-left2">Constituency:</li>-->
<li><?php htmlout($result['constituency']); ?></li>
<li><?php htmlout($result['qualifications']); ?></li>
</ol>
<form action="?" method="post">
<div id="buttons">
<input type="hidden" name="id" value="<?php htmlout($result['id']); ?>">
<a href="?more&id=<?php htmlout($result['id']); ?>">View full profile</a>
<!--<input type="submit" name="action" value="Edit" class="buttons">
<input type="submit" name="action" value="Delete" class="deletebutton">-->
</div>
</form>
<?php endforeach; ?>
<?php endif; ?>
现在在上面的摘录中有一个h1标签,只能在页面顶部显示一次。
我知道因为它在foreach循环中,所以每个结果都会输出这个h1标签。
事情是,我知道它可能非常简单,但我不确定如何在循环上方输出此值,因此它只显示一次。
该值位于名为$ results的数组中,所以我认为我可以使用以下内容:
<?php htmlout($results['constituency']); ?>
现在看看这个,我可以看到这没有意义,因为$ results数组可能包含几个选区结果。
即使返回了几个结果,它们都将包含相同的选区值,所以我想我正在寻找类似的结果:
第二种选择可能是要走的路,但是我还有另一个问题。
到目前为止我学到的PHP总是将结果输出到数组中。所以我会有类似的东西:
$sql = "SELECT * FROM pt";
$s = $pdo->query($sql);
然后我将如上所示使用:
foreach ($s as $row)
{
$results[] = array(.........
如何将查询结果存储到变量中? E.g。
$constituency = "SELECT name from constituency WHERE id = $constituencyid";
$s = $pdo->query($constituency);
$result = $s (Not allowed as this is a PDO object but hopefully you can see what I am thinking)
好的,非常感谢任何人都能给我的任何帮助。
答案 0 :(得分:0)
实际上,有一个名为array_unique()
的PHP函数,您应该查看PHP手册:http://php.net/manual/en/function.array-unique.php
答案 1 :(得分:0)
使用以下函数获取constituency
的数组
$constituencies = array_map(function($val){
return $val['constituency'];
}, $results);
使用以下代码获取变量中的constituency
$sql = "SELECT name from constituency WHERE id = ".$pdo->quote($constituencyid);
$stmt = $pdo->query($sql);
$row = $stmt->fetch();
$constituency = $row['name'];