【问题标题】:Symfony2 - How to sort a merged array of objects?Symfony2 - 如何对合并的对象数组进行排序?
【发布时间】:2014-07-17 11:24:04
【问题描述】:

我有 4 个数组,我试图将属性视图从最高到最低排序。

我正在尝试弄清楚如何对合并后的数组进行排序。

现在,对于合并的数组,我从 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 将视图从高到低排序:

$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);

【问题讨论】:

    标签: sorting symfony merge usort


    【解决方案1】:

    仅使用 1 个 postSort 和一个带有所有 4 个实体的合并数组的 usort 即可解决。

    只需使用 1 个 postSort 功能:

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

    对所有 4 个数组的 array_merge 使用 1 个 usort:

    $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'));
    

    【讨论】:

      猜你喜欢
      • 2021-04-17
      • 1970-01-01
      • 1970-01-01
      • 2010-10-12
      • 1970-01-01
      • 2011-08-18
      相关资源
      最近更新 更多