-2

I have an array coming into a function that looks something like this:

$array = array(
    'SomeKey' => array()
    'SomeOtherKey' => array()
);

and I would like to have the csv file, when opened in excel, look like:

SomeKey

---- rows of data -----

SomeOtherKey

---- Rows of Data ---

the function I wrote only processes arrays of this matter:

$array = array(array(...));


public function createCvsObject($array, $name = 'report.csv'){       
    $this->headers($name);
    if (count($array) == 0) {
        return null;
    }

    $df = fopen("php://output", 'w');
    fputcsv($df, array_keys(reset($array)));

    foreach ($array as $row) {
        fputcsv($df, $row);
    }

    fclose($df);
}

What would I have to change to get the expected out put I want?

LogicLooking
  • 916
  • 1
  • 16
  • 32

2 Answers2

1

Can try the below code if it helps you:

fputcsv($df, 'somekey');

foreach ($array['somekey'] as $row) {
    fputcsv($df, $row);
}

fputcsv($df, 'someOtherkey');

foreach ($array['someOtherkey'] as $row) {
    fputcsv($df, $row);
}
0

From the looks of it, you're only missing your key row. Otherwise, please edit your question to mention what's wrong with your code, what output you get, what output you expect, etc.

foreach ($array as $key => $row) {
    fwrite($df, $key);
    fputcsv($df, $row);
}
SolarBear
  • 4,534
  • 4
  • 37
  • 53
  • The problem with this is that its appending `SomeKey` to the first row of data, and then above the first row of data I see `0 | 1 | 2` – LogicLooking Oct 23 '13 at 18:49