Reputation: 95
I have data in text file separate by colon like
3306250027:JOHN:Male:Manager
3306250028:JOHN:Male:Manager
3306250029:JOHN:Male:Employee
I want to use line 1 and ignore line 2 that have column 2 and 4 duplicated and do nothing with line 3. The out put that I want
3306250027:JOHN:Male:Manager
3306250029:JOHN:Male:Employee
I try to use array_unique() but I don't know what to do, some from my code
$lines = file('file.txt');
$result = array_unique($lines, SORT_REGULAR);
Upvotes: 0
Views: 43
Reputation: 41810
In order to reduce the list to one value for each name/title combination, you can group the lines by those two values. Here's an example of one way to do that:
foreach ($lines as $line) {
list(,$name,,$title) = explode(':', $line);
$groups[$name][$title] = $groups[$name][$title] ?? $line;
}
By setting $groups[$name][$title]
to the value $groups[$name][$title] ?? $line
, we ensure that only the first value for each name/title combination will be used. This will result in an array like this:
[
"JOHN": [
"Manager": "3306250027:JOHN:Male:Manager",
"Employee": "3306250029:JOHN:Male:Employee"
]
]
After you have the data in that grouped form, you just need to extract the unique values back out of it for your result. That's pretty easy to do with array_walk_recursive
.
array_walk_recursive($groups, function($line) use (&$result) {
$result[] = $line;
});
Upvotes: 1