我有一个PHP循环,可以生成一周中的几天。
$wk = array(1 => "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday");
foreach ($wk as $k => $v) {
...
}
产生类似这样的东西:
Monday
... additional HTML code here
Tuesday
... additional HTML code here
Wednesday
... additional HTML code here
我还有另一个查询,它以下列数组格式将数据输出到数组 $ items 中:
Array
(
[0] => stdClass Object
(
[id] => 1
[day] => 2
[created] => 2014-10-22 21:32:52
)
[1] => stdClass Object
(
[id] => 3
[day] => 3
[created] => 2014-10-22 21:35:19
)
[2] => stdClass Object
(
[id] => 4
[day] => 3
[created] => 2014-10-22 21:35:23
)
)
我遇到的问题是数组。有一个值对应于工作日。例如:[day] => 3对应于$ k == 3(星期二)。
如何将对象中的数据输出到与星期几相对应的插槽中?我可以每天运行一个单独的查询,但这似乎有点低效,咖啡因还没有完全开始......
答案 0 :(得分:1)
$items
$items[]->day
$wk
如果我理解你的问题,这样的事情应该有效:
foreach ($items as $item) {
echo $wk[$item->day];
// Or if you want to update it
$item->day = $wk[$item->day];
}
或如果您想保留原始循环(foreach ($wk as $k => $v)
),请将查询结果编入day
键的索引,以便您的数组如下所示:
Array
(
[1] => Array
(
// objects of that day
),
[4] => Array
(
// etc
)
)
然后你可以改变原来的foreach循环:
foreach ($wk as $k => $v) {
foreach ($items[$k] as $item) {
}
}