Skip to content

Instantly share code, notes, and snippets.

@juniorb2ss
Created February 21, 2014 13:06
Show Gist options
  • Save juniorb2ss/9133914 to your computer and use it in GitHub Desktop.
Save juniorb2ss/9133914 to your computer and use it in GitHub Desktop.
Datamapper object to array, with id as array key
/**
* Convert the entire $object->all array result set into an array of
* associative arrays.
* @see to_array
* @param DataMapper $object The DataMapper Object to convert
* @param array $fields Array of fields to include. If empty, includes all database columns.
* @param string $key_field Key Field array
* @return array An array of associative arrays.
*/
function all_to_array($object, $fields = '', $key_field = '')
{
$result = array();
if ( $key_field == '' )
{
foreach($object as $o)
{
$result[] = $o->to_array($fields);
}
}
else
{
foreach($object as $o)
{
if ( ! is_array($fields) )
{
$result[$o->{$key_field}] = $o->{$fields};
}
else
{
$result[$o->{$key_field}] = $o->to_array($fields);
}
}
}
return $result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment