Getting data from DB into array with foreach
I have a database table with events in them:
id | title | description | day_start | day_end | user_id
1 | sometitle | blabla | 2011-04-20 | 2011-04-21 | 1
2 | title 2 | bleble | 2011-04-20 | 2011-04-21 | 1
I want to read this out form my db with a foreach loop.
I want to store this into $data[day_start]
For example: $data['2011-04-21']
should contain two arrays in this case, one for each event. I'm not sure how to do this. I had the following code (in CI):
(the $start
argument is a date, like 2011-04-20).
public function get_event_data($start)
{
$data = array();
$query = $this->db->query(
"SELECT *
FROM tblEvents
WHERE user_id = '" . $this->session->userdata('id') . "'
AND day_start = '" . $start . "';"
);
foreach($query->result() as $row)
{
$data[$row->day_start] = array(
'title' => $row->title,
'description' => $row->description,
'day_start' => $row->day_start,
'day_end' => $row->day_end,
'time_start' => $row->time_start,
'time_end' => $row->time_end,
'user_id' => $row->user_id
);
}
return $data;
}
However, as expected, this only outputs the SECOND event (since I'm using '=', which overrides the data that gets put in the array the first time):
Array ( [2011-04-20] => Array ( [title] => 开发者_运维技巧Test Event 2 [description] => second event. [day_start] => 2011-04-20 [day_end] => 2011-04-20 [time_start] => 12 [time_end] => 13 [user_id] => 1 ) )
(the data here differs from the one i provided at the top, but it's about the idea, not the data).
I tried using .= but then php complains that there's no such index to be found.. Cause I didn't initiate it and I'm trying to add to it.
So then, I tried with a if(isset($data[$start])
block, but that didn't really get me anywhere either.
I want to grab all the events for a particular day and put them in an array so I can process it further in my application. Thanks a lot.
try
$data[$row->day_start][] = array(
The second set of []
will create an auto-iterative array, so no data will be over written.
Unless I misunderstand, CI allows you to return an array of results, which is doing the exact same thing as your code above.
return $query->result_array();
Would do it.
If you don't want all your data in the array, then don't select *
and only take what you require.
精彩评论