我的数据来自数据库,并且一直是grouped by
day_id
,因此数组按 排序day_id
。
提供代码+示例输出,有点难以用语言表达。
到目前为止,我从这个公认的答案中得到了灵感,但我需要稍作调整。
$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 中,但我无法弄清楚逻辑。如果我用<h3>
打开的 div 替换 ,我不知道在哪里放置关闭</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>
希望这是有道理的-谢谢