My application returns an array of objects and each object contains a "name" key which sometimes is repeated in other objects.
How can I filter the duplicates?
This is an array having duplicates
[
{"name":"India","id":2,"uid":"1M16"},
{"name":"Delhi","id":3,"uid":"1M16"},
{"name":"India","id":4,"uid":"1M16"}
]
The output I want is:
[
{"name":"India","id":2,"uid":"1M16"},
{"name":"Delhi","id":3,"uid":"1M16"}
]
And this is how I am getting this array from database.
$results_1 = Sheet::whereIn('uid', $results_1)->select('name', 'id', 'uid')->get();
You can use distinct()
if you want a single column. In your case you need groupBy()
to get the unique values.
$results_2 = Sheet::whereIn('uid', $results_1)->select('name', 'id', 'uid')->groupBy('name')->get();
you are using same
$results_1
variable to hold the new values and inwhereIn
clause. consider using different variables.
And to use groupBy()
you have to change some things in your database config file. in your config>database.php
file add this lines in mysql configuration.
'modes' => [
'STRICT_TRANS_TABLES',
'NO_ZERO_IN_DATE',
'NO_ZERO_DATE',
'ERROR_FOR_DIVISION_BY_ZERO',
'NO_AUTO_CREATE_USER',
'NO_ENGINE_SUBSTITUTION'
]
And don't forget to clear the cache after changing anything in the config file.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments