多维不规则数组到PHP中的CSV [英] multidimensional irregular array to CSV in PHP

查看:91
本文介绍了多维不规则数组到PHP中的CSV的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,我知道有很多主题专用于该主题,但是我没有找到/找到解决问题的正确方法,对不起,如果我错过了什么. 所以我得到了一个看起来像这样的数组:

First of all I know there are many threads dedicated to this topic but I didn't found/figured out the right solution for my problem, sorry if I missed something. So I got an array that looks like this:

Array
(
[0] => id1
[1] => Array
    (
        [0] => Url1
    )

[2] => id2
[3] => no url found
[4] => id3
[5] => Array
    (
        [0] => url3.1
        [1] => url3.2
        [2] => url3.3
     )
)

并且我想构建一个如下的csv:

and i want to build a csv looking like:

id1,url1
id2,no url found
id3,url3.1,url3.2,url3.3

尝试过

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

,但它仅捕获子数组中的元素(如果存在).我应该如何处理?提前致谢!

but it grabs only the elements of the subarrays if they exist. How should I approach that? Thanks in advance!

推荐答案

我建议从原始数组创建一个中间数组,该数组具有所需的结构,然后从该数组创建CSV输出:

I would suggest creating an intermediate array from the original one, which would have the desired structure, and then create the CSV output from that:

// Preprocess the array to get the format needed for the CSV output
for ($i = 0; $i < count($array); $i += 2) {
    $result[] = is_array($array[$i+1])
        ? array_merge([$array[$i]], $array[$i+1])
        : [$array[$i], $array[$i+1]];
}

foreach($result as $row){
   fputcsv($csv, $row, ',');
}

看到它在 eval.in 上运行.

这篇关于多维不规则数组到PHP中的CSV的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆