Created
April 13, 2017 07:09
-
-
Save paulofreitas/5fa0a95ae22586b96a7d36a8ad90647e to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// Requires Laravel | |
$json = <<<JSON | |
[{"name": "Taylor Otwell", | |
"country": { | |
"name": "United States" | |
} | |
}, | |
{"name": "Paulo Freitas", | |
"country": { | |
"name": "Brazil" | |
} | |
}, | |
{"name": "Taylor Otwell", | |
"country": { | |
"name": "Brazil" | |
} | |
} | |
] | |
JSON; | |
$users = collect(json_decode($json))->sort(function ($leftUser, $rightUser) { | |
// Using PHP 7 spaceship operator | |
return $leftUser->name <=> $rightUser->name | |
?: $leftUser->country->name <=> $rightUser->country->name; | |
// Compatible with older PHP | |
return strcmp($leftUser->name, $rightUser->name) | |
?: strcmp($leftUser->country->name, $rightUser->country->name); | |
}); | |
var_dump($users->toArray()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment