Reputation: 2221
I am trying to create a new CSV file from an existing CSV file with additional data. I used fgetcsv to access the data from the existing CSV file and put it inside an array. After putting the csv file contents to an array, the array turned out as a 2-D array with data that looks like this:
Array {
[0] =>
Array {
[0] => "Data1", "Data2", Data3
}
}
So what I did was create a new array from this by imploding first the array values then exploding like so:
for($i = 0; $i < $myArray; $i++) {
$tempString = implode(" ", $myArray);
$tempArray = explode (" ", $tempString);
}
With this my array now looks like so:
Array {
[0] => "Data1"
[1] => "Data2"
[3] => "Data3" //endDate
}
Array {
[0] => "Data1"
[1] => "Data2"
[3] => "Data3" //endDate
}
Now, I would like to add a fourth value on the array for startDate. I want the startDate to be equal to the endDate + 1. So for example the endDate is 20th November, then the endDate for the next Array is 21st November. The thing is I'm not entirely sure how to implement that. I've tried adding this inside the for loop just like pretty much all the examples and articles I've read:
$d3 = $tempArray[3]; //Data3
if($d3 == $previous) {
//do some things here
}
$previous = $d3 + 1;
The thing with this is the dates tend to be in groups. For example arrays 1-8 is 20th November then array 9-20 is 30th November. Because of this, only the first date among these "groups" get the previous value so only array 9 would get 21st November. How can I tell my code that while the end date is the same, it does not change the start date? Then if it does, it should get the previous date and add 1 day to it? Please help.
Also, I know there might be something wrong with how I'm handling the arrays so if anybody knows how to handle this better, faster and more efficiently, I would appreciate it.
Upvotes: 0
Views: 172
Reputation: 810
$resultant_array = array(
array(
'0' => 'hello',
'1' => 'world',
'2' => '20-11-2009'
),
array(
'0' => 'hi',
'1' => 'check',
'2' => '20-11-2009'
),
array(
'0' => 'hi',
'1' => 'newcheck',
'2' => '30-11-2009'
),
array(
'0' => 'hell0',
'1' => 'newcheck',
'2' => '30-11-2009'
)
);
foreach($resultant_array as $rk => &$rv) {
if($rk == 0) {
$end_date = $rv[2];
}
if($rv[2] == $end_date) {
continue; // ignore as its neigther the first group
} else {
if($rk) $rv[] = date('d-m-Y', strtotime('+1 day',strtotime($rv[2])));
$end_date = $rv[2];
}
}
This is just a sample iteration and you should also think of parsing the csv contents in a much better way.
Upvotes: 1