ina*_*abt 13 php sorting collections doctrine doctrine-1.2
我需要这样的东西:
$products = Products::getTable()->find(274);
foreach ($products->Categories->orderBy('title') as $category)
{
echo "{$category->title}<br />";
}
Run Code Online (Sandbox Code Playgroud)
我知道这是不可能的,但是......如果不创建Doctrine_Query,我该怎么做呢?
谢谢.
小智 31
你也可以这样做:
$this->hasMany('Category as Categories', array(...
'orderBy' => 'title ASC'));
Run Code Online (Sandbox Code Playgroud)
在您的架构文件中,它看起来像:
Relations:
Categories:
class: Category
....
orderBy: title ASC
Run Code Online (Sandbox Code Playgroud)
我只是在看同样的问题.您需要将Doctrine_Collection转换为数组:
$someDbObject = Doctrine_Query::create()...;
$children = $someDbObject->Children;
$children = $children->getData(); // convert from Doctrine_Collection to array
Run Code Online (Sandbox Code Playgroud)
然后你可以创建一个自定义排序函数并调用它:
// sort children
usort($children, array(__CLASS__, 'compareChildren')); // fixed __CLASS__
Run Code Online (Sandbox Code Playgroud)
compareChildren的位置如下:
private static function compareChildren($a, $b) {
// in this case "label" is the name of the database column
return strcmp($a->label, $b->label);
}
Run Code Online (Sandbox Code Playgroud)
你可以使用集合迭代器:
$collection = Table::getInstance()->findAll();
$iter = $collection->getIterator();
$iter->uasort(function($a, $b) {
$name_a = (int)$a->getName();
$name_b = (int)$b->getName();
return $name_a == $name_b ? 0 : $name_a > $name_b ? 1 : - 1;
});
foreach ($iter as $element) {
// ... Now you could iterate sorted collection
}
Run Code Online (Sandbox Code Playgroud)
如果要使用__toString方法对集合进行排序,则会更容易:
foreach ($collection->getIterator()->asort() as $element) { /* ... */ }
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
19939 次 |
| 最近记录: |