Create CSV from multidimensional array with fputcs

2020-04-07 18:37发布

问题:

I'm trying to get a multidimensional array into a csv file. data in the array is as such:

Array
(
 [0] => Array
    (
        [product_id] => 1111
        [name] => Alcatel One Touch Idol 2
        [keyword] => alcatel-one-touch-idol-2
        [options] => Array
            (
                [0] => Array
                    (
                        [price] => 54.0000
                    )

                [1] => Array
                    (
                        [price] => 42.0000
                    )

                [2] => Array
                    (
                        [price] => 10.0000
                    )

                [3] => Array
                    (
                        [price] => 
                    )

                [4] => Array
                    (
                        [price] => 
                    )

                [5] => Array
                    (
                        [price] => 
                    )

                [6] => Array
                    (
                        [price] => 
                    )

                [7] => Array
                    (
                        [price] => 
                    )

                [8] => Array
                    (
                        [price] => 
                    )

                [9] => Array
                    (
                        [price] => 
                    )

            )

    )

[1] => Array
    (...... etc)

I get all of the top level data, but then once it reaches the options array, i get Array to string conversion errors. So i have two issue, i firstly need to see why i am getting this error, and then i need to fputcsv all of this information on one line per product.

So far i have this to parse the array into a csv:

$output = fopen("php://output",'w') or die("Can't open php://output");
            header("Content-Type:application/csv"); 
            header("Content-  Disposition:attachment;filename=product_catalog.csv"); 
            $first_line = explode(",", $first_line);
            fputcsv($output, $first_line);
            foreach($csv as $file) {
                fputcsv($output, $file);
            }
            fclose($output) or die("Can't close php://output");

If anyone could help me i'd really appreciate that. regards.

回答1:

I would suggest to flatten each array first:

foreach ($csv as $file) {
    $result = [];
    array_walk_recursive($file, function($item) use (&$result) {
        $result[] = $item;
    });
    fputcsv($output, $result);
}

In each iteration it would create an array like this:

[1111, 'Alcatel One Touch Idol 2', 'alcatel-one-touch-idol-2', 54, 42, ...]


回答2:

foreach ($data as $line) {
    foreach($line as $array){
        foreach($array as $result){
            fputcsv($f,$result,",");
        }
    }
}

i know its an old question but you could also use this