【问题标题】:Doctrine_Collection __toString() type of functionalityDoctrine_Collection __toString() 类型的功能
【发布时间】:2012-03-13 04:05:19
【问题描述】:

有人对根据特定列名将 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 类提供的内置方法。

【问题讨论】:

    标签: php orm doctrine tostring doctrine-collection


    【解决方案1】:

    最后只写了一个包装方法来根据特定列将 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;
    }
    

    【讨论】:

      猜你喜欢
      • 2011-07-08
      • 2012-02-26
      • 2020-08-03
      • 1970-01-01
      • 2012-04-12
      • 2023-04-04
      • 1970-01-01
      • 2012-04-05
      • 1970-01-01
      相关资源
      最近更新 更多