-1

有人对基于特定列名将 Doctrine_Collection 转换为 CSV 的最佳方法有任何想法吗?

示例数组:

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)

我想结束:

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

现在我可以通过以下方式轻松做到这一点:

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

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

但是,我想看看是否有使用 Doctrine_Collection 类提供的内置方法的更优雅的解决方案。

4

1 回答 1

0

最后只写了一个包装方法来根据特定列将 Doctrine_Collections 转换为 CSV:

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;
}
于 2012-03-15T01:02:43.137 回答