I'm a PHP developer who typically uses arrays in lieu of objects, and I'd like to know if there are any best practices for object manipulation based on key values.
Take the following multi-dimensional array of events, typical of something you'd pull directly out of the database.
$events = array(
0=>array(
'eventid'=>1,
'title'=>'First Event',
'date'=>'20131010'
),
1=>array(
'eventid'=>2,
'title'=>'Second Event',
'date'=>'20131022'
),
2=>array(
'eventid'=>3,
'title'=>'Third Event',
'date'=>'20131010'
),
),
For display purposes in my template, I want to make this a multi-dimensional array based on the date first. This is fairly easy transformation that I use a helper function for.
assoc($events,'date','eventid');
Resulting in:
$events = array(
20131010=>array(
1 => array(
'eventid'=>1,
'title'=>'First Event',
'date'=>'20131010'
),
3 => array(
'eventid'=>3,
'title'=>'Third Event',
'date'=>'20131010'
),
),
20131022=>array(
2 => array(
'eventid'=>1,
'title'=>'First Event',
'date'=>'20121010'
),
),
),
In this way, I can easily run through the array on the template side for each date, create a header and for that date, and then display events for that day underneath.
I could go ahead and try to make a similar assoc() function for Objects, but it strikes me this should be a fairly common thing and there may be a standard way of doing it. If you had an object instead of an array for $events, how would you go about formatting it the second way I've described, or would you?
One additional piece of information: I am using CodeIgniter, in case it has some helper functions that I'm not aware of that could be useful.