Search code examples
phpsortingsymfonymergeusort

Symfony2 - How to sort a merged array of objects?


I have 4 arrays that I am trying to sort the property views from highest to lowest.

I am trying to figure out how to sort the merged arrays.

Right now with the merged arrays I have highest to lowest views from 1 set and then highest to lowest views in the 2nd set.

How do I sort both sets so I have the highest to lowest views for the 4 arrays in one merged array?

(e.g., currently: merged array 1: highest-lowest views / merged array 2: highest to lowest views --- I want highest to lowest for all 4 in 1 set)

I have 2 sets of arrays of objects that is sorted:

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;
}

I am using usort to sort the views from highest to lowest:

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

Solution

  • Resolved by using just 1 postSort and one usort with a merged array of all 4 entities.

    Just use 1 postSort function:

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

    Use 1 usort with a array_merge of all 4 arrays:

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