I wanna create an array that follow my "CSV logic" but I'm struggling.
Here is kind of an example of the content of the CSV:
+------------+----------+-------------+---------+
| Name | Duration | User | Level |
+------------+----------+------------+----------+
| Bestall | 7 Days | | T |
| Bestleft | 6 Days | | ST |
| Turn | 2 Days | Brother | |
| Jump | 4 Days | Sister | |
| Bestdown | 1 Day | | ST |
| Play | 1 Day | Sister | |
+------------+----------+------------+----------+
So, what I try to achieve is to create a dimension per Level.
T stands for Title and ST for SubTitles.
With this example, the resulting array would be:
[Bestall] => Array
(
[Duration] => 7 Days
[Bestleft] => Array
(
[Duration] => 6 Days
[0] => Array
(
[Name] => Turn
[Duration] => 2 Days
[User] => Brother
)
[1] => Array
(
[Name] => Jump
[Duration] => 4 Days
[User] => Sister
)
)
[Bestdown] => Array
(
[Duration] => 1 Day
[0] => Array
(
[Name] => Play
[Duration] => 1 Day
[User] => Sister
)
)
)
My actual code for this (not working)
$data = array();
if (($handle = fopen($filename, 'r')) !== FALSE)
{
while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
{
$level = $row[count($row)-1];
$titled = false;
if($level=='T') {
$titled = $row[0];
$data[$titled] = $row;
}
elseif($level=='ST')
$data[$titled][] = $row;
array_push($data[$titled], $row);
}
fclose($handle);
}
Here is the php code you need:
$data = array();
$t = false;
$st = false;
if (($handle = fopen($filename, 'r')) !== FALSE)
{
$header = fgetcsv($handle, 1000, $delimiter);
while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
{
$level = $row[count($row)-1];
if($level=='T') {
$t = $row[0];
$data[$t][$header[1]] = $row[1];
}
elseif($level=='ST'){
$st = $row[0];
$data[$t][$st][$header[1]] = $row[1];
}
else{
$tmp_row = array(
$header[0] => $row[0],
$header[1] => $row[1],
$header[2] => $row[2]
);
$data[$t][$st][] = $tmp_row;
}
}
fclose($handle);
}
print_r($data);