moprocto
2 months ago
368
4
Laravel

Get distinct associative arrays based on matching value pairs

Posted 2 months ago by moprocto

I have a messaging system in my app and I'm pulling my hair out trying to figure out the best way to give the user a menu to select which conversation they want to read. I'm trying to mirror the GroupMe style menu where on the left are your conversations. This conversation list is dynamic so the most recent conversations are at the top and update while you are using the app.

I'm using Laravel 7 and Firebase

Here's the data from my backend (prettified)

Array
(
    [-MC1kTfrrDHY3ZbidJ4Q] => Array
        (
            [from] => lSUfZ4sgEJd
            [message] => test message four no more!
            [startedAt] => 2020-07-12 11:21:10
            [to] => CWgPqdn3YweN
        )

    [-MC09BsjtXP0izITsThf] => Array
        (
            [from] => CWgPqdn3YweN
            [message] => test message three
            [startedAt] => 2020-07-11 11:20:19
            [subject] => -MC00BHCZlXUp25C5nlS
            [to] => lSUfZ4sgEJd
        )

    [-MC1kAi1niswXtjY_h4s] => Array
        (
            [from] => CWgPqdn3YweN
            [message] => test message two
            [startedAt] => 2020-07-12 11:19:52
            [to] => lSUfZ4sgEJd
        )

    [-MC1kOtfnIlAYtmJsD-a] => Array
        (
            [from] => CWgPqdn3YweN
            [message] => test message one
            [startedAt] => 2020-07-12 11:18:50
            [to] => lSUfZ4sgEJd
        )
     [-MC1kOtfnIlAhgcufu] => Array
        (
            [from] => CWgPqdn3YweN
            [message] => test message zero
            [startedAt] => 2020-07-12 11:00:50
            [to] => YLisXjk07w93
        )
)

I want to get the latest, distinct conversations no matter if I'm the sender or receiver. The end result I want will look like this

Array
(
 [-MC1kTfrrDHY3ZbidJ4Q] => Array
        (
            [from] => lSUfZ4sgEJd
            [message] => test message four no more!
            [startedAt] => 2020-07-12 11:21:10
            [to] => CWgPqdn3YweN
        )
 [-MC1kOtfnIlAhgcufu] => Array
        (
            [from] => CWgPqdn3YweN
            [message] => test message zero
            [startedAt] => 2020-07-12 11:00:50
            [to] => YLisXjk07w93
        )
)

Anybody mind providing guidance on this? I have tried following along with responses on StackOverflow https://stackoverflow.com/questions/25561707/get-unique-value-of-one-attribute-from-array-of-associative-arrays but I lose the $key of the array, which is the ID of the message.

Please sign in or create an account to participate in this conversation.