dpi10335 2016-09-23 14:05
浏览 71
已采纳

PHP:如何只从数组中打印一次键和每个项的每个值?

So here's my code:

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

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 $result->devices. 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.

  • 写回答

2条回答 默认 最新

  • douxiaomang5640 2016-09-23 14:49
    关注

    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));
    }
    fclose($fp);
    

    This way, you will get this:

    deviceID,description,status
    1,desc1,status14
    2,desc2,status15
    3,desc3,status16
    4,desc4,status17
    

    Is this what you need?

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题