📅  最后修改于: 2023-12-03 15:32:33.088000             🧑  作者: Mango
In Laravel, Collections provide a variety of useful methods that allow you to manipulate data. One of the methods available to Collections is the unique() method, which returns a new collection by removing any duplicated values from the collection. The unique() method can be used on any kind of collection, whether it is an array, an object, or even a nested collection.
The syntax for the unique() method is as follows:
$collection->unique([$key])
Where $collection
is the collection you want to remove duplicates from and $key
is an optional parameter that specifies the key to use to determine uniqueness. If no key is specified, the entire item is checked for uniqueness.
Here are some examples of how you can use the unique() method:
$array = [1, 2, 3, 2, 4, 5, 1];
$unique_array = collect($array)->unique()->values()->all();
print_r($unique_array);
Output:
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
)
In the above example, we have an array with duplicate values. We pass this array to a collection and apply the unique() method to remove duplicates. The values() method is used to re-index the array and all() method is used to retrieve all the items.
class User {
public $name;
public $email;
public function __construct($name, $email) {
$this->name = $name;
$this->email = $email;
}
}
$users = [
new User('John Doe', 'johndoe@test.com'),
new User('Jane Doe', 'janedoe@test.com'),
new User('John Doe', 'johndoe@test.com'),
new User('Bob Smith', 'bobsmith@test.com')
];
$unique_users = collect($users)->unique('email')->values()->all();
print_r($unique_users);
Output:
Array
(
[0] => stdClass Object
(
[name] => John Doe
[email] => johndoe@test.com
)
[1] => stdClass Object
(
[name] => Jane Doe
[email] => janedoe@test.com
)
[2] => stdClass Object
(
[name] => Bob Smith
[email] => bobsmith@test.com
)
)
In the above example, we have an array of User objects with some objects having duplicate email addresses. We pass this array to a collection and apply the unique() method with the email field as the key to remove duplicates. The values() method is used to re-index the array and all() method is used to retrieve all the items.
The unique() method is very useful for removing duplicate values from a collection. Whether you are working with arrays, objects, or nested collections, the unique() method can help you keep your data clean and consistent.