I want to import a csv file from a html form and process it in php. Dynamically create a table and append it to my div for preview purposes.
I want array only of unique records inside the table.
I have following code in php:
$tmpName = $_FILES['blk_csv']['tmp_name'];
$csvAsArray = array_unique((array_map('str_getcsv', file($tmpName))),SORT_REGULAR);
$table_data = '<table id="template_table" name="template_table" class="table">';
$csvAsArrayU = $csvAsArray;
for ($i = 0; $i < count($csvAsArrayU); $i++) {
if($i == 0){
$table_data .= '<thead><tr>';
for($h = 0 ; $h < count($csvAsArrayU[$i]); $h++){
$table_data .= '<th class="text-center">'.$csvAsArrayU[$i][$h].'</th>';
}
$table_data .= '</tr></thead><tbody>';
}
else{
$table_data .= '<tr id="row-'.$i.'">';
for($r = 0 ; $r < count($csvAsArrayU[$i]); $r++){
$table_data .= '<td class="text-center">'.$csvAsArrayU[$i][$r].'</td>';
}
$table_data .= '</tr>';
}
}
$table_data .= ' </tbody></table>';
My csv structure
NAME,EMAIL
Morris,[email protected]
Morris,[email protected]
Morris,[email protected]
Jacob,[email protected]
If you print_r($csvAsArray) it gives me following output:
Array ( [0] => Array ( [0] => NAME [1] => EMAIL ) [1] => Array ( [0] => Morris [1] => [email protected] ) [8] => Array ( [0] => Jacob [1] => [email protected] ) )
If you notice the index for third element is 8 and not 2. Thus the DataTable library fails to load the data and shows something like this :
Can any one guide me how to fix this ? Or may be a different approach to load only unique rows in array ?

array_uniquepreserves the keys. The entry in question is presumably in that position in the source CSV, simple as that. You could also runarray_uniqueonfileand only map the remaining lines for CSV. As it stands, you're iterating a lot of duplicates that are then discarded. That would also give you consecutive indices without having to runarray_values.foreachloop, rather than accessing the array with a count-basedforloop. That's what they're meant for.