Kyle Hudson
Kyle Hudson

Reputation: 898

php csv upload remove duplicates

Whats the quickest way to upload a CSV with PHP whilst removing duplicates (the phone number).

Example:

Kyle,Hudson,447000000000,[email protected],CUST-1,CUST-2,CUST-3
John,Doe,447000000001,[email protected],CUST-1,CUST-2,CUST-3
John,Doe,447000000001,[email protected],CUST-1,CUST-2,CUST-3
Jack,Doe,447000000004,[email protected],CUST-1,CUST-2,CUST-3 

Should become:

Kyle,Hudson,447000000000,[email protected],CUST-1,CUST-2,CUST-3
John,Doe,447000000001,[email protected],CUST-1,CUST-2,CUST-3
Jack,Doe,447000000004,[email protected],CUST-1,CUST-2,CUST-3 

I know how to upload the CSV ect, I just need to know how to remove the duplicates.

Would I need to create an array or something similar and then use a function like array_unique?

Your help is appriciated :)

Upvotes: 2

Views: 1972

Answers (6)

Bogdan Constantinescu
Bogdan Constantinescu

Reputation: 5356

The code you need to make this work is pretty staight forward!

Here you go:

<?php

$myCSV = file($_FILES['file']['tmp_name']);
//duplicates
var_dump($myCSV);
$myCSV = array_unique($myCSV);
//unique
var_dump($myCSV);

//now handle it how you need

Upvotes: 0

Yoram de Langen
Yoram de Langen

Reputation: 5499

You can use array_unique, but then you need to create a array.. You got a strange long number in your csv?(447000000000) i assume thats unique for every user. So make a key from that number and do it like underneave here.. So i suggest to create a array like this:

Array(
  [447000000000] => Array (
    "name" => "Kyle"
    "lastname" => "Hudson",
    "id" => 447000000000
    [.........]
  ),
  [447000000001] => Array (
    "name" => "John"
    "lastname" => "Doe",
    "id" => 447000000001
    [.........]
  )
  [.........]
)

and now you can use array_unique on that

Upvotes: 0

Cybercartel
Cybercartel

Reputation: 12592

You want to read the csv by each line and then you want to use an auxilliary array to store and check for duplicates.

Upvotes: 0

osm
osm

Reputation: 4218

Also you can use array_flip for passing values as array key.

Keys of array cannot be duplicate.

Upvotes: 0

zod
zod

Reputation: 12427

array_unique — Removes duplicate values from an array

http://php.net/manual/en/function.array-unique.php

If data is so huge PHP arrays are expensive

Upvotes: 0

Gerben Jacobs
Gerben Jacobs

Reputation: 4583

Yeah, like you said. Upload it, put all entries in an array, throw array_unique over it and continue.

Upvotes: 2

Related Questions