Jump to content

CSV Group Duplication


thecase

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
https://forums.phpfreaks.com/topic/289210-csv-group-duplication/
Share on other sites


$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]";

}

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.

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.