Jump to content

CSV Group Duplication


thecase
Go to solution Solved by CroNiX,

Recommended Posts

Hi 

 

I am reading in data from a csv file

if (($handle = fopen("data.csv", "r")) !== FALSE) {

while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {

echo "User Name: $data[0]";
echo "Booking IDs: $data[1]";

}

echo "<hr>";

The problem is some of the usernames are duplicated so get outputted the same user name 20 times but with different IDs, obviously but I am unsure how to group them together. 

 

I can't seem to figure out how to write if the next username is the same as current then just add another ID not go through the entire loop. 

 

Any ideas?

 

Thanks

 

Link to comment
Share on other sites

  • Solution

$last_user = ''; //track the last user
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$user = $data[0];
if ($user !== $last_user) //if the current user isn't the same, store as last user and display name
{
  $last_user = $user;
  echo "User Name: $user";
}

echo "Booking IDs: $data[1]";

}
Link to comment
Share on other sites

You have to keep track of the last one printed:

 

$lastUser = null;
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
  if ($data[0] != $lastUser) {
    echo "User Name: $data[0]";
    $lastUser = $data[0];
  }
echo "Booking IDs: $data[1]";

}

echo "<hr>";
Of course, this would depend on the user records being grouped together in the input. If they are not, you could load all of the data into a multi-dimensional array.
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.