简体   繁体   中英

Turning a nested associative array in php into a CSV file

I working on a PHP issue and have an associative array that looks like this:

(
  [2019-03-22T2:26:03-04:00] => Array
      (
          [0] => Array
              (
                  [A] => 1
                  [B] => 1
                  [C] => 2
              )

      )

  [2019-03-23T2:27:04-04:00] => Array
      (
          [0] => Array
              (
                  [A] => 1
              )

      )
)

I'm trying to turn this data into a CSV that looks like this:

NAME                              COUNT
2021-07-15T10:46:16-04:00
      A                             1
      B                             1
      C                             2
2021-07-15T10:46:17-04:00
      A                             1

I've done this before, going from an array to csv, with a simple associative array but getting it in the format above is not working for me. This is the code that I have tried:

The variable $statArray holds the array that I need to be on a CSV.

  $fp = fopen('test.csv', 'w');
  foreach ($statArray as $fields)
  {
    foreach ($key as $v)
    {
        fputcsv($fp, $v);
    }
  }

Thank you for any help.

That's an odd format, but you need to write the main array key and then get the nested keys and values and write those:

foreach ($statArray as $date => $array)
{
    fputcsv($fp, [$date]);  //write main key
    
    foreach ($array as $values)
    {
        foreach ($values as $name => $count)
        {
            fputcsv($fp, [$name, $count]); //write key and value
        }
    }
}

This might make more sense:

2021-07-15T10:46:16-04:00    A    1
2021-07-15T10:46:16-04:00    B    1
2021-07-15T10:46:16-04:00    C    2
2021-07-15T10:46:17-04:00    A    1

If so then:

foreach ($statArray as $date => $array)
{        
    foreach ($array as $values)
    {        
        foreach ($values as $name => $count)
        {
            fputcsv($fp, [$date, $name, $count]); //write date and key and value
        }
    }
}

Either way, you state CSV but it looks like you are showing tabs not commas. If so you would need:

fputcsv($fp, [$date, $name, $count], "\t");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM