Nico V Nico V - 26 days ago 4x
PHP Question

PHP: How do I print the key from array only once and every value for each item?

So here's my code:

foreach ($result->devices as $device) {
$flag = false;
foreach ($device as $key => $value) {
$flag = true;

What I try to achieve is to only print the key (description, brand, etc...) only once but print the value of all those keys for every device found. This is to make it eventually save as an .csv

Note: $result = a multidimensional array where I'm only interested in the devices section of it, hence the
The way this works now is it only prints the first key for every device found, what I get now looks something like:

string 'deviceId' (length=8) // keeps getting repeated
int 4268
string 'beschrijving nr 53' (length=18)
string 'deviceId' (length=8) // keeps getting repeated
int 4267
string 'Weer een tooltje' (length=16)

What I try to get is something resembling:

string 'deviceId' (length=8)
string 'description' (length=??)
string 'status' (length=??)
... // rest of keys, followed by devices
int 4268
string 'beschrijving nr 53' (length=18)
... // rest of values, followed by other devices
int 4267
string 'Weer een tooltje' (length=16)

I'm sure it's something simple like the wrong order of operation or moving something in/out a certain loop, but after having tried various variations, I'm none the wiser.

So to whom may solve this mystery, I thank you greatly.


So, I suppose, your data looks kind of like this?

$result = (object)[];

$result->devices = [
    ['deviceId' => 1, 'description' => 'desc1', 'status' => 'status14'],
    ['deviceId' => 2, 'description' => 'desc2', 'status' => 'status15'],
    ['deviceId' => 3, 'description' => 'desc3', 'status' => 'status16'],
    ['deviceId' => 4, 'description' => 'desc2', 'status' => 'status17'],

Then to create a CSV file from it I would go like this:

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

foreach($result->devices as $i => $device)
    // First row? Write headers (keys) first!
    if($i == 0) fputcsv($fp, array_keys($device)); 

    // Write data rows
    fputcsv($fp, array_values($device));

This way, you will get this:


Is this what you need?