来自数组的html输出逻辑
Posted
技术标签:
【中文标题】来自数组的html输出逻辑【英文标题】:html output logic from array 【发布时间】:2013-02-18 22:03:03 【问题描述】:我的数据来自一个数据库,一直是grouped by
day_id
,所以数组按照day_id
排序。
提供的代码 + 示例输出,有点难以用语言表达。
到目前为止,我的灵感来自this accepted answer,但我需要稍作调整。
$array = array(
0 => array(
'id' => '5',
'day_id' => '1',
'Foo' => array(
'id' => '28',
'name' => 'My day_id is 1'
)
),
1 => array(
'id' => '6',
'day_id' => '1',
'Foo' => array(
'id' => '29',
'name' => 'My day_id is 1'
)
),
2 => array(
'id' => '7',
'day_id' => '2',
'Foo' => array(
'id' => '30',
'name' => 'My day_id is 2'
)
),
3 => array(
'id' => '8',
'day_id' => '3',
'Foo' => array(
'id' => '31',
'name' => 'My day_is 3'
)
)
);
我的输出代码:
$day = 0;
foreach($array as $a)
// $a['day_id'] = 1, condition is true. output header once.
if($day != $a['day_id'])
echo '<h3>The Day is ' . $a['day_id'] . '</h3>' . "\n";
// output the elements Foo key content.
echo $a['Foo']['name'] . "\n";
// store the current value to compare on the next iteration
// $a['day_id'] will eventually be 2, causing the condition to fire again.
$day = $a['day_id'];
这个输出:
<h3>The Day is 1</h3>
My day_id is 1
My day_id is 1
<h3>The Day is 2</h3>
My day_id is 2
<h3>The Day is 3</h3>
My day_is 3
我现在想将每个“Day”包装在一个 DIV 中,但我无法弄清楚其中的逻辑。如果我用开放的 div 替换 <h3>
,我不知道在哪里放置结束 </div>
。到目前为止,我的尝试只是导致每天都有一个 open
div,但不是封闭的,因此它们是嵌套的,而不是分开的。
我不能放</div><div class="day-X">
,因为开头会有一个额外的</div>
,这会破坏布局。
期望的输出:
<div class="day-1">
<h3>The Day is 1</h3>
My day_id is 1
My day_id is 1
</div>
<div class="day-2">
<h3>The Day is 2</h3>
My day_id is 2
</div>
<div class="day-3">
<h3>The Day is 3</h3>
My day_is 3
</div>
希望这是有道理的 - 谢谢
【问题讨论】:
+1 用于提供可用的 php 数组! 您需要存储天数,然后检查数组。我使用一小部分天数+唯一更新了我的答案.. 【参考方案1】:您将需要循环两次,一次用于日期,另一次用于具有这一天的项目。在不使用任何其他 SQL 查询的情况下,您需要先将日期存储在数组中。然后你可以循环这些天,每天你会回显<div>
和天标题,最后你会回显</div>
。
在 foreach 中,您可以再次循环使用相同的数组来检查每个项目是否在同一天。如果是,则回显项目的名称,否则不执行任何操作。
我已经测试了这段代码,你可以检查一下,如果你有任何问题,请告诉我。
foreach($array as $day)
$days[] = $day['day_id']; // store all the days in an array
// now days[] has [1,1,2,3]
$days = array_unique($days); // get unique days only no duplicated
//now days[] has [1,2,3]
foreach($days as $d) // for each day
echo '<div class = "day-'.$d.'">';
echo '<h3>The Day is ' . $d . '</h3>' . "\n";
foreach($array as $a) // check all other items if the item has the same day then echo
if($a['day_id'] == $d)
echo $a['Foo']['name'] . "\n";
echo '</div>';
输出:
<div class = "day-1">
<h3>The Day is 1</h3>
My day_id is 1
My day_id is 1
</div>
<div class = "day-2">
<h3>The Day is 2</h3>
My day_id is 2
</div>
<div class = "day-3">
<h3>The Day is 3</h3>
My day_is 3
</div>
【讨论】:
以上是关于来自数组的html输出逻辑的主要内容,如果未能解决你的问题,请参考以下文章