我有一个大数组对象,看起来像这样:
$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
)
)
我需要以这样一种方式对其进行重组,即我可以根据一天的价值输出结果。例如,所有记录都与第=3天相关,依此类推
我已经有了一个基于一周中几天的代码结构,所以我需要为这个数组运行一个单独的循环,以插入与现有结构中每一天匹配的记录。
例如:
$wk = array(1 => "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday");
foreach ($wk as $k => $v) {
...
// insert records from $items
}
有没有一种方法可以重写$items数组来实现这一点?如果是,如何?感谢您的建议。
- 创建新阵列
- 迭代旧数组
- 在新数组中创建索引(如果不存在)
- 将旧数组的项添加到新索引
像这样的东西应该起作用:
// Create new array
$daySortedItems = array();
// Iterate over old array
foreach ($items as $item) {
// Create index in new array if it doesn't exist
if (! isset($daySortedItems[$item->day])) {
$daySortedItems[$item->day] = array();
}
// Add item of old array to new index
$daySortedItems[$item->day][] = $item;
}
希望这能结合你之前的问题,解决你的问题。请注意,像这样抛出热修复程序被认为是不好的做法。一个更好的解决方案是在较低级别上解决该问题:在查询数据库时,直接在day
键上对结果集进行索引。