2014-07-17 66 views
0

我有4个数组,我试图从最高到最低排序属性视图。我想弄清楚如何排序合并数组。Symfony2 - 如何对合并的对象数组进行排序?

现在与合并阵列我有从1集最高到最低的意见,然后从第2集最高到最低的意见。

如何对两组进行排序,以便在一个合并数组中有4个数组的最高到最低视图?

(例如,目前:合并数组1:最高最低视图/合并阵列2:最高到最低的观点---我想最高到最低的所有4个1组)

我有2套

private static function postSort($post, $post2) 
{ 
    return $post->getViews() == $post2->getViews() ? 0 : ($post->getViews() < $post2->getViews()) ? 1: -1; 
} 

private static function postSort2($post3, $post4) 
{ 
    return $post3->getViews() == $post4->getViews() ? 0 : ($post3->getViews() < $post4->getViews()) ? 1: -1; 
} 

我使用usort从最高到最低的意见进行排序:只用1 postSort和一个我们解决

$posts = $this->getDoctrine()->getRepository('AcmeDemoBundle:Post') 
    ->getPosts(); 

$posts2 = $this->getDoctrine()->getRepository('AcmeDemoBundle:Post2') 
    ->getPosts2(); 

$posts3 = $this->getDoctrine()->getRepository('AcmeDemoBundle:Post3') 
    ->getPosts3(); 

$posts4 = $this->getDoctrine()->getRepository('AcmeDemoBundle:Post4') 
    ->getPosts4(); 

$postTotal1 = array_merge($posts, $posts2); 

usort($postTotal1, array($this, 'postSort')); 

$postTotal2 = array_merge($posts3, $posts4); 

usort($postTotal2, array($this, 'postSort2')); 

$total = array_merge($postTotal, $postTotal2); 

回答

1

指将其排序的对象数组与所有4个实体合并的阵列。

只需使用1个postSort功能:

private static function postSort($item1, $item2) 
{ 
return $item1->getViews() == $item2->getViews() ? 0 : ($item1->getViews() < $item2->getViews()) ? 1: -1; 
} 

使用1 usort所有4个阵列的array_merge:

$posts = $this->getDoctrine()->getRepository('AcmeDemoBundle:Post') 
    ->getPosts(); 

$posts2 = $this->getDoctrine()->getRepository('AcmeDemoBundle:Post2') 
    ->getPosts2(); 

$posts3 = $this->getDoctrine()->getRepository('AcmeDemoBundle:Post3') 
    ->getPosts3(); 

$posts4 = $this->getDoctrine()->getRepository('AcmeDemoBundle:Post4') 
    ->getPosts4(); 

$postTotal = array_merge($posts, $posts2, $post3, $post4); 

usort($postTotal, array($this, 'postSort')); 
相关问题