我目前正在使用foreach循环管理HTML内容的显示,如下所示:
<?php
echo "<table class=\"tableau\">
<tr bgcolor=\"#a72333\" class=\"first\">
<th>Repere</th>
<th>Niveau</th>
<th>Enseigne</th>
<th>Activités</th>
</tr>
<tbody>";
$db= JFactory::getDBO();
$query = 'SELECT baseData, sid, fid FROM XXXX_sobipro_field_data';
$db->setQuery($query);
$results = $db->loadObjectList();
$j = 0;
foreach ($results as &$value) {
if ($value->sid == 55) {
if ($value->fid == 20) {
$repere = $value->baseData;
}
if ($value->fid == 16) {
$level = $value->baseData;
}
if ($value->fid == 22) {
$title = $value->baseData;
}
if ($value->fid == 17) {
$activity = $value->baseData;
}
if ($value->fid == 21) {
$display = $value->baseData;
}
if ($value->sid == 56) {
if ($value->fid == 20) {
$repere1 = $value->baseData;
}
if ($value->fid == 16) {
$level1 = $value->baseData;
}
if ($value->fid == 22) {
$title1 = $value->baseData;
}
if ($value->fid == 17) {
$activity1 = $value->baseData;
}
if ($value->fid == 21) {
$display1 = $value->baseData; // <- Here it's $display_NUM where _NUM = 1. It goes on and on until 24 for now.
}
}
[...]
// It ends at if ($value->fid == 83) but It could be more , it's not always the same ID
}
所以我将变量命名为$title_NUM
,$activity_NUM
,...,其中_NUM
是一个从&#34开始的数字;没有&#34;,它以24结束现在,但如果我的表格中有更多数据,可能会更多。
获取数据后,我会显示如下的html:
if ($display == 1) {
echo "<tr bgcolor=\"#eaeaeb\">
<td valign=\"top\">".$j"</td>
<td align=\"top\">".$level."</td>
<td valign=\"top\"><a data-lightbox=\"width:600;type:iframe;\" href=\"LINK\">".$title."</a></td>
<td align=\"top\">".$activity."</td>
</tr>";
$repere = $j;
$j++;
}
同样的情况发生在这里我用手显示每个html&#34;&#34; ,O没有任何循环来完成这项工作。
有没有办法只用循环来完成工作?
编辑2
我已经尝试过这样的事情:
$i = 0;
$j = 0;
foreach ($results as&$value) {
while (i <= 83) {
if ($value->sid == $i) {
if ($value->fid == 20) {
$repere[$j] = $value->baseData;
}
if ($value->fid == 16) {
$level[$j] = $value->baseData;
}
if ($value->fid == 22) {
$title[$j] = $value->baseData;
}
if ($value->fid == 17) {
$activity[$j] = $value->baseData;
}
if ($value->fid == 21) {
$display[$j] = $value->baseData;
}
$j += 1;
}
$i++;
}
}
答案 0 :(得分:0)
您应该为需要循环的变量使用数组。所以,而不是使用:
$display, $display1, $display2, ....
$activity, $activity1, $activity2, ....
定义一维或二维数组,在您的情况下会更好:
$output = array();
$check_sids = array(55, 56); /* Edit this list... */
比...类似的东西。
foreach ($results as &$value) {
if (in_array($value->sid, $check_sids)) {
$add = array(
'repere' => ($value->fid == 20) ? $value->baseData : '',
'level' => ($value->fid == 16) ? $value->baseData : '',
'title' => ($value->fid == 22) ? $value->baseData : '',
'activity' => ($value->fid == 17) ? $value->baseData : '',
'display' => ($value->fid == 21) ? $value->baseData : ''
);
$output[] = $add;
};
};
之后,通过循环$output
来输出html会很容易。