1

I have problem with convert array. I have structure like as

$threeDimensionalArray = [
[
    [
        'name' => 'name1',
    ],
    [
        'name' => 'name2',
    ],

],

[
    [

        'time' => 123,
        'anyField'=>22222,
        'anyField1'=>22222,
        'anyField2'=>22222
    ],

    [
        'time' => 457,
        'anyField'=>22222,
        'anyField1'=>22222,
        'anyField2'=>22222
    ],
],

];

I need convert this array to two dimensional and save each array to csv file via fputscsv

example

first line in CSV

'name1','name2',

second line

123, 457, etc

p.l
  • 39
  • 5
  • 2
    Possible duplicate of [How to Flatten a Multidimensional Array?](https://stackoverflow.com/questions/1319903/how-to-flatten-a-multidimensional-array) – David Lemon Dec 05 '18 at 08:55

2 Answers2

1

This solution will help in your specific case:

$to_csv = [];
foreach ($threeDimensionalArray as $first_level) {
    foreach ($first_level as $second_level) {
        foreach ($second_level as $key => $value) {
            $to_csv[$key][] = $value;
        }
    }
}

$fp = fopen('file.csv', 'w');

foreach ($to_csv as $fields) {
    fputcsv($fp, $fields);
}

fclose($fp);

The idea is to firstly configure array to two layers array with grouping by key and use fputcsv() afterwards.

0

I resolve this problem :)

foreach ($threeDimensionalArray as $firstDimensional) {
$array= [];
foreach ($firstDimensional as $twoDimensional) {
    $array[] = $twoDimensional['name'] ?? null .$twoDimensional['time'] ?? null;
}
fputcsv($fp, $array);
$returnArray[]=$array;

}

p.l
  • 39
  • 5