有人对基于特定列名将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类提供的内置方法的更优雅的解决方案。
最终只编写了一个包装器方法,将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;
}