Reputation: 59
I have a csv upload functionality that saves in to my database table. I would like to modify this to read an extra row of data and format the array accordingly.
The table will look like this:
Date | Cost Type 1 | Cost Type 2 | Cost Type 3 |
---|---|---|---|
£50.00 | £10.00 | £90.00 | |
01/01/21 | 1 | 3 | 10 |
02/01/21 | 5 | 4 | 12 |
I am saving the cost heading against each figure. So before I get to saving the actual data, I want to read a cost price for each type and save it in to my array as well.
$formattedArray = [];
foreach($the_array as $element) {
$formattedArray[] = [
"cost" => array_keys($element)[0],
"demand" => array_values($element)[0],
];
}
The final array should look like this:
array(
[0] => Array
(
[date] => 01/01/21
[cost] => Cost Type 1
[demand] => 1
[total] => £50.00
)
[1] => Array
(
[date] => 01/01/21
[cost] => Cost Type 2
[demand] => 3
[total] => £10.00
)
[2] => Array
(
[date] => 01/01/21
[cost] => Cost Type 3
[demand] => 10
[total] => £90.00
)
)
My csv upload function looks like this:
if ($this->request->data['file']['error'] === UPLOAD_ERR_OK){
$i = 1;
if (($file = fopen($this->request->data['file']['tmp_name'], "r")) !== FALSE) {
while (($row = fgetcsv($file, 0, ',', '"')) !== FALSE) {
if ($i == 1){
$header = $row;
}else{
if (count($header) == count($row)){
$uploads[] = array_combine($header, $row);
}else{
$error_rows[] = $row;
}
}
$i++;
}
fclose($file);
}
}
Upvotes: 1
Views: 45
Reputation: 13948
I think I got your question, You mean to say that the data doesn't start from the 2nd row, instead the 2nd row contains an additional piece of info and then the data starts from 3rd row.
In that case all you need to do is parse the 2nd row just as you are parsing the 1st row, and then store and use the value in/from variables.
if ($this->request->data['file']['error'] === UPLOAD_ERR_OK) {
$i = 1;
$finalArray = [];
if (($file = fopen($this->request->data['file']['tmp_name'], "r")) !== FALSE) {
while (($row = fgetcsv($file, 0, ',', '"')) !== FALSE) {
if ($i == 1) {
$header = $row;
} elseif ($i == 2) {
$priceInfo = $row;
} else {
if (count($header) == count($row)) {
$rowArray = [];
for ($i = 1; $i < count($row); $i++) { // Starting from 1 as we need to skip the first column
$rowArray[] = [
"cost" => $header[$i],
"demand" => $row[$i],
"total" => $priceInfo[$i],
"date" => $row[0],
];
}
$finalArray[] = $rowArray;
} else {
$error_rows[] = $row;
}
}
$i++;
}
fclose($file);
}
}
Upvotes: 1