Commit eb7b8209 authored by Sylvain's avatar Sylvain

🐛 csv_to_collection - Array to collection

parent 8a83ab04
......@@ -122,43 +122,52 @@ if ( !function_exists('objectize')) {
if ( !function_exists('csv_to_collection')) {
/**
* Retourne une collection d'object standard à partir d'une chaine de caractère de type csv
* @param string $csv Le contenu du CSV
* @param string $delimiter Le séparateur du CSV
* @return Collection La collection
* @param string $csv Le contenu du CSV
* @param string $delimiter Le séparateur du CSV
* @param string $without_column_name Si la 1ère ligne ne correspond pas aux entêtes de colonnes
* @return Collection La collection
*/
function csv_to_collection(string $csv, string $delimiter = ';')
function csv_to_collection(string $csv, string $delimiter = ';', $without_column_name = false)
{
$datas = array();
$collect = collect();
$headers = [];
// Conversion du string en tableau brut
$lines = explode(PHP_EOL, $csv);
// Récupération des lignes (en prenant en compte les retours à la ligne dans les contenus)
preg_match_all('/[^"\n]*("[^"]*\n*")?.*/', $csv, $matches);
$lines = array_filter($matches[0]);
// Parsage du CSV
foreach ($lines as $line => $value) {
if ($line == 0) {
$headers = explode($delimiter, $value);
if (!$without_column_name && $line == 0) {
$headers = str_getcsv($value, $delimiter);
} else {
$values = explode($delimiter, $value);
$values = str_getcsv($value, $delimiter);
if (count($values) > 1) {
$datas[] = $values;
}
}
}
// Création de la collection
foreach ($datas as $line => $data) {
$obj_line = new stdClass;
foreach ($headers as $col => $name) {
if (isset($data[$col])) {
$col_name = str_replace('-', '_', Str::slug($name));
$value = trim(trim($data[$col], '"'));
$obj_line->{$col_name} = $value;
// Si la première ligne du csv correspond aux entêtes de colonnes
if (!$without_column_name) {
// Création de la collection
foreach ($datas as $line => $data) {
$obj_line = new stdClass;
foreach ($headers as $col => $name) {
if (isset($data[$col])) {
$col_name = str_replace('-', '_', Str::slug($name));
$value = trim(trim($data[$col], '"'));
$obj_line->{$col_name} = $value;
}
}
}
$collect->push($obj_line);
$collect->push($obj_line);
}
} else {
$collect = collect($datas);
}
return $collect;
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment