GPiter
GPiter

Reputation: 799

Write in a csv values whitout a foreach

I have this array :

$array = [
    'data' => [
        0 => 2678
        1 => 2378
    ],
    'active' => [
        0 => 866
        1 => 111
    ]
    ..........
]

I want to put in a csv like that

data active 2678 866 2378 111

I tried like this :

fputcsv($fp,array_keys($array));
fputcsv($fp,array_values($array));

But something not working. I have only header shown in the csv, I mean only data active whitout data. Please help me

Upvotes: 0

Views: 74

Answers (1)

iainn
iainn

Reputation: 17417

array_values doesn't do anything except return your existing array without any keys, so you're still passing a 2D array to fputcsv, which isn't something it can work with.

Fundamentally, you're looking to perform an operation on every "row" in your array. This is absolutely what a foreach loop is for, so I'm not sure why you'd be trying to avoid one. Unless you've got a very particular reason to avoid them (and I can't imagine what that might be), that's the structure you should be using.

To get your code working, all you need to do is wrap a loop around your second call to fputcsv:

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

Edit: Sorry, I didn't notice that the array was transposed in the question. If you want to work with that, you'll need to add the line:

$array = array_map(null, ...array_values($array));

before displaying the data.

See https://3v4l.org/AoRcQ for a full example.

Upvotes: 1

Related Questions