我有数据库表,其中包含字段id,文本和类型。在类型 I 中可以有值 1 和 2。如果返回的类型为 1,我想显示一个 html 输出,如果类型为 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 ?>
我尝试像这样在 if 中使用 foreach:
<?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.
在这种情况下,我会这样说,先生:
$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中,我们不能以这种方式内联打印所有内容,这就是为什么我们:
- 声明一个具有两个值的数组,它们是需要检查的"$data['type']"。通过这样做,我们将类型声明为键和与每个键对应的数组。
- 当我们循环遍历结果时,我们将结果推送到上面相应键的正确数组中。 在具有"类型"2 的结果上传递 $output[$data['type']] 与执行完全相同:$output['2']。 下一个 [] 表示"将该元素推入该数组",因此我们实际上是根据其键填充数组。
- 由于数组的结构再次循环,我们通过获取 TYPE("键")和它的值来循环它,即 $data['text'],我们首先打印类型(动态地,这样如果明天你想添加一个类型 3,你可以这样做没有很多问题),然后是与其类型对应的值。
输出:
<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"
)
);
// 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'];
}
}