0

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);
6
  • 1
    It is always best to show us some code or it looks like you jsut want us to code for you Commented Nov 24, 2020 at 16:59
  • Are you sure you want to remove Both line 1 and 2? Do you not want to leave one of those lines in the file and just remove the duplicated one Commented Nov 24, 2020 at 17:00
  • sorry I jus want to use only line one and ignore line 2 Commented Nov 24, 2020 at 17:04
  • 1
    This is quite easy if there are only a few rows in the file and if the duplicates will always be consecutive. Is that the case? Commented Nov 24, 2020 at 17:08
  • some file the duplicate line not consecutive and have a thousand of lines Commented Nov 24, 2020 at 17:15

1 Answer 1

1

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; 
});
Sign up to request clarification or add additional context in comments.

Comments

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.