1

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.

1 Answer 1

1

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");
Sign up to request clarification or add additional context in comments.

3 Comments

IMHO having only fputcsv($fp, [$date, $name, $count]); in the inner loop would be a far sane-r CSV output. But if this is what OP really wants...
Edited, forgot a nesting.
Thank you! I got it!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.