1

I have some JSON data that I have sorted by "sites" using usort

    usort($data,function($a,$b) {
    return strnatcasecmp($a['site'],$b['site']);
  });

Which results in the following

Array (
    [0] => Array
        (
            [time] => 2017-07-15 15:43:45
            [user] => ast125
            [site] => facebook
        )

    [1] => Array
        (
            [time] => 2017-07-12 04:59:11
            [user] => ast111
            [site] => facebook
        )

    [2] => Array
        (
            [time] => 2017-07-19 12:45:14
            [user] => ast133
            [site] => facebook
        )

    [3] => Array
        (
            [time] => 2017-07-19 12:45:14
            [user] => ast133
            [site] => google
        )

    [4] => Array
        (
            [time] => 2017-07-19 12:45:14
            [user] => ast125
            [site] => facebook

        )

.... and so on

I'm stuck because now I'm not sure how to approach sorting the users per site. Right now, the order is

facebook - ast125

facebook - ast111

facebook - ast133

google - ast133

google - ast125

But I would like the users to be sorted while in their site group

facebook - ast111

facebook - ast125

facebook - ast133

google - ast125

google - ast133

Right now, I am considering breaking the JSON array into multiple arrays (by site), and then sort the new site array by users, and then merge them back into one...

Is there an easier way for me to approach this using usort or another PHP function?

1

1 Answer 1

1

Is there an easier way for me to approach this using usort or another PHP function?

Certainly.

usort($data, function(array $a, array $b) : int {
    return strcasecmp($a['site'], $b['site']) ?: strcasecmp($a['user'], $b['user']);
});

(Demo this online)

When $a and $b differ in 'site', the first strcasecmp() will return a nonzero value, so that value will be used. When they are identical, the first strcasecmp() will return 0, which is treated as false, so the ?: operator will use the result of the second comparison.

This pattern can be chained to an arbitrary number of comparisons.

Sign up to request clarification or add additional context in comments.

2 Comments

Hmm, another question.. how would I go about adding another condition? Once the sites are sorted, then users are sorted, I'd like the users:site sorted by time
Throw another ?: comparison() onto the end of the statement. If you want to compare numbers, use $b["property"] - $a["property"].

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.