Reputation: 12512
I have a large array object that looks something like this:
$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
)
)
I need to restructure it in such a way that I could output results based on a day value. For example all records associate with day = 3 and so on.
I already have a structure of code that is based on days of a week, so I need to run a separate loop for this array to insert the records that match each day of the existing structure.
For example:
$wk = array(1 => "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday");
foreach ($wk as $k => $v) {
...
// insert records from $items
}
Is there a way to rewrite my $items array to accomplish this? If yes, how? Appreciate any suggestions.
Upvotes: 0
Views: 25
Reputation: 1560
Something like this should work:
// 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;
}
Hope that this, in combination with your previous question, solves your problem. Do note that throwing hot-fixes in like this is considered bad practice. A better solution is to fix the problem at a lower level: when querying the database, index the result set on the day
key directly.
Upvotes: 1