Search code examples
phpormdoctrinetostringdoctrine-collection

Doctrine_Collection __toString() type of functionality


Anyone have any ideas on the best way to convert a Doctrine_Collection to a CSV based on a specific column name?

Example array:

array
  0 => 
    array
     'id' => string '2' (length=1)
     'name' => string 'metallica' (length=14)
     'created_at' => string '2011-09-02 23:15:15' (length=19)
     'updated_at' => string '2011-10-05 02:51:23' (length=19)
  1 => 
    array
      'id' => string '7' (length=1)
      'name' => string 'coal chamber' (length=13)
      'created_at' => string '2011-09-06 00:24:02' (length=19)
      'updated_at' => string '2011-10-05 02:51:11' (length=19)
  2 => 
    array
      'id' => string '14' (length=2)
      'name' => string 'slayer' (length=14)
      'created_at' => string '2011-10-05 02:48:58' (length=19)
      'updated_at' => string '2011-10-05 02:50:15' (length=19)

I would like to end up with:

string 'metallica,coal chamber,slayer' (length=29)

Now I could easily do this with something like:

foreach ($this->getBands()->toArray() as $array) {
    $names[] = $array['name'];
}

var_dump(implode(',', $names));

But, I'd like to see if there is a more elegant solution using the built-in methods provided by the Doctrine_Collection class.


Solution

  • Ended up just writing a wrapper method to transform Doctrine_Collections to CSVs based on a specific column:

    public static function toString(array $options)
    {
        $collection = $options['collection'];
        $columnName = $options['columnName'];
        $separator = (isset($options['separator'])) ? $options['separator'] : ', ';
    
        foreach ($collection->toArray() as $element) {
    
            if (isset($element[$columnName])) {
                $columnValues[] = $element[$columnName];
            }
        }
    
        return (isset($columnValues)) ? implode($separator, $columnValues) : null;
    }