【发布时间】:2013-02-18 22:03:03
【问题描述】:
我的数据来自一个数据库,一直是grouped byday_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 数组!
-
您需要存储天数,然后检查数组。我使用一小部分天数+唯一更新了我的答案..
标签: php html foreach logic output