Home > Enterprise >  Array into a csv with PHP
Array into a csv with PHP

Time:11-04

I have the next foreach:

foreach(json_decode($result[$k], "true") as $result) {
    fputcsv($fp, $result);
}

and if I put a var_dump of that result it will return a list of arrays like:

  ["Id"]=> string(7) "1"
  ["Name"]=> string(29) "Name"
  ["Description"]=> string(19) "Description"
  ["Address"]=> string(27) "Address"
  ["Schedule"]=> array(7) {
    [0]=> array(2) {
        ["startHour"]=> string(5) "00:00"
        ["stopHour"]=> string(5) "23:59"
    }
    [1]=> array(2) {
        ["startHour"]=> string(5) "00:00"
        ["stopHour"]=> string(5) "23:59"
    }
    [2]=> array(2) {
        ["startHour"]=> string(5) "00:00"
        ["stopHour"]=> string(5) "23:59"
    }
    . . .
  }

If I put fputcsv($fp, $result) in that foreach loop, everything works good until Schedule. The line from csv looks like:

1, Name, Description, Address, Array. 

But, what I want instead of "Array" I want something like

00:00-23:59. 

Like:

1, Name, Description, Address, 00:00-23:59, 00:00-23:59, 00:00-23:59

(for each day of the week). Can anyone help me with this? Thank you!

CodePudding user response:

You can do this in your foreach, if you have always set up 7 schedule entries

$result = array_values($result);
$schedule = $result[4];
unset($result[4]);
$schedule = array_map(function($a){ return implode('-',$a);},$schedule);
$result = array_merge($result,$schedule);

Note: You should give the foreach variable another name e.g. $item, because you are using a variable named $result in json_decode

CodePudding user response:

You will need to process the 2 arrays seperately.

I had to fake up some data as an array so I missed out the json conversion part of your code

$json = 
[
    ["Id"=>"1", "Name"=>"Name", "Description"=>"Description","Address"=> "Address",
     "Schedule" => [ ["startHour"=> "00:00", "stopHour"=> "23:59"],
                    ["startHour"=> "00:00", "stopHour"=> "23:59"],
                    ["startHour"=> "00:00", "stopHour"=> "23:59"]
                ]
    ],
    ["Id"=>"2", "Name"=>"Fred", "Description"=>"Bloke","Address"=> "1 main st",
     "Schedule" => [ ["startHour"=> "02:00", "stopHour"=> "20:59"],
                    ["startHour"=> "03:00", "stopHour"=> "21:59"],
                    ["startHour"=> "04:00", "stopHour"=> "22:59"]
                ]
    ]   
];

$fp = fopen('tst.csv', 'w');
foreach($json as $result) {
    $t1 = [ $result['Id'], $result['Name'], $result['Description'], $result['Address'] ];
    // process the schedule array now seperately
    $t2 = [];
    foreach($result['Schedule'] as $sch){
        $t2[] = $sch['startHour'] . '-' . $sch['stopHour'];
    }
    fputcsv($fp, array_merge($t1,$t2));
}
fclose($fp);

RESULTS

1,Name,Description,Address,00:00-23:59,00:00-23:59,00:00-23:59
2,Fred,Bloke,"1 main st",02:00-20:59,03:00-21:59,04:00-22:59
  • Related