Reputation: 24142
I am pulling out a number of notes associated with a time from my database.
I'm not too hot with multidimensional arrays, but I'd like to group all the events together under the time that they occurred.
Here is one of my queries:
SELECT TIME(date) AS time, followupNote, completed, entityRef
FROM entity_followups
WHERE userRef = ?
AND DAY(date) = ?
AND MONTH(date) = ?
AND YEAR(date) = ?
An example output from this could be three rows, the first column being the time, then the note, completed, then the entityRef.
I want any rows with the same time to be grouped together in the array, e.g.
Array (
[0] => Array (
[0] => 12:00:00
[1] => Array (
[0] => note
[1] => completed
[2] => entityRef
)
[2] => Array (
[0] => note2
[1] => completed2
[2] => entityRef2
)
)
)
But later on there will be other queries that collect other kinds of events which need to be added into the top level array, and if an event has the same time as one in the subarray, it needs to be added into that.
Upvotes: 1
Views: 65
Reputation: 9709
I'll assume that your existing code is enough for getting the time and value. Thus you will have these items in whatever variable or data structure you choose to use. For the purposes of this answer, I will assume these values already exist in the individual variables: $time
, $value[0]
, $value[1]
, and $value[2]
. Further, I will assume that the results are being loaded into the array $timesAndValues[]
I think the key is to have the $timesAndValues[]
array indexed on the corresponding time:
if (isset($timesAndValues[$time]))
{ //The corresponding sub-array already exists, so we just need to load it
//Push the array of values into the sub-array
array_push($timesAndValues[$time], $value);
}
else
{ //The corresponding sub-array does not exist yet, so we need to create it and load it
//Create the sub-array
$timesAndValues[$time] = array($time);
//Push the array of values into the sub-array
array_push($timesAndValues[$time], $value);
}
Upvotes: 2