Symfony2 - 如何对合并的对象数组进行排序?

问题描述 投票:0回答:1

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

我想弄清楚如何对合并的数组进行排序。

现在,通过合并的数组,我拥有第一组中最高到最低的视图,然后是第二组中最高到最低的视图。

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

(例如,当前:合并数组 1:最高-最低视图/合并数组 2:最高到最低视图 --- 我想要 1 组中所有 4 个视图的最高到最低)

我有 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);
php sorting symfony merge usort
1个回答
1
投票

仅使用 1 个 postSort 和 1 个 usort 以及所有 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'));
© www.soinside.com 2019 - 2024. All rights reserved.