我的数据库表包含字段 id ,文字和类型。在类型中,我可以将值 1 和 2 。如果返回的类型是1,我想显示一个html输出,如果type是2,我想显示其他输出。
表:
id text type
1 Some text 1
2 Blah Blah 2
所以我的简单查询SELECT * from table
将返回值数组。在我的HTML中,我想输出它:
<?php foreach ($model as $data): ?>
<h4>Text where status is 1:</h4>
echo $data['text'];
<h4>Text where status is 2:</h4>
echo $data['text'];
<?php endforeach ?>
我试过在这样的foreach中使用if:
<?php if ($data['type'] == "1"): ?>
<h4>Text where status is 1:</h4>
echo $data['text'];
<?php else: ?>
<h4>Text where status is 2:</h4>
echo $data['text'];
<?php endif ?>
但这并没有真正起作用。我的解决方案是否有一个查询将返回类型为1的文本,另一个类型为2的查询?或者有更好的解决方案吗?
我想输出如下:
<h4> Text where status is 1 </h4>
First text.
Second text.
Third text.
<h4> Text where status is 2 </h4>
Fourth Text.
Fifth Text.
答案 0 :(得分:2)
在这种情况下,我会这样做,先生:
$outputs = array("1" => array(),"2" => array());
foreach ($model as $data) {
$outputs[$data['type']][] = $data['text'];
}
foreach ($outputs as $type => $values) {
echo "<h4>Text where status is {$type}: </h4><br />";
foreach ($values as $text) {
echo $text . " <br />";
}
}
说明:
我们不能在PHP中以这种方式内联打印所有内容,这就是我们原因:
输出:
<h4>Text where status is 1: </h4><br />hello <br />ohai dude <br /><h4>Text where status is 2: </h4><br />hello dude <br />
从这样的输入数组:
$model = array(
0 => array( "id" => "0",
"type" => "1",
"text" => "hello"
),
1 => array( "id" => "1",
"type" => "2",
"text" => "hello dude"
),
2 => array( "id" => "2",
"type" => "1",
"text" => "ohai dude"
)
);
答案 1 :(得分:0)
// connect to db first
$link = mysqli_connect('host','user','pass','database');
// get something from db
$result = mysqli_query($link, "SELECT * FROM table ORDER BY type");
// loop through result and echo
$flag1 = false;
$flag2 = false;
while($data = mysqli_featch_array($result, MYSQLI_ASSOC)) {
if($data['type'] == "1") {
if(!$flag1) {
echo '<h4>Text where status is 1:</h4>';
$flag = true;
}
echo $data['text'];
} else {
if(!$flag2) {
echo '<h4>Text where status is 2:</h4>';
$flag = true;
}
echo $data['text'];
}
}