我正在创建php代码以将下面的json转换为csv
Array
(
[data] => Array
(
[0] => Array
(
[DESC] => bla bal bal
[SOLD] => 0
[contact_no] => 1234
[title] => Hiiiii
[price] => 10900
[big_image] => Array
(
[0] => http://example.com/images/user_adv/14.jpg
[1] => http://example.com/images/user_adv/15.jpg
)
[small_image] => Array
(
[0] => http://example.com/images/user_adv/small/14.jpg
[1] => http://example.com/images/user_adv/small/15.jpg
)
[tpe] => user
)
[1] => Array
(
[DESC] => fo fo fof ofof
[SOLD] => 0
[contact_no] => 234522
[title] => Hellooooo sddf
[price] => 0
[big_image] => Array
(
[0] => http://example.com/images/user_adv/154.jpg
[1] => http://example.com/images/user_adv/144.jpg
[2] => http://example.com/images/user_adv/147.jpg
)
[small_image] => Array
(
[0] => http://example.com/images/user_adv/small/154.jpg
[1] => http://example.com/images/user_adv/small/144.jpg
[2] => http://example.com/images/user_adv/small/147.jpg
)
[tpe] => user
)
)
[pis] => 3
[totals] => 23
[curpage] => 1
[total_ads] => 71
)
我一直在使用以下代码将其导出到.csv
$fp = fopen("output.csv","w");
foreach ($json['data'] as $fields) {
fputcsv($fp, $fields);
}
fclose($fp);
我可以很好地转换它,但我面临一个小问题,即子数组是big_image& small_image没有出现在输出文件.csv(行为空)
中 [big_image] => Array
(
[0] => http://example.com/images/user_adv/154.jpg
[1] => http://example.com/images/user_adv/144.jpg
[2] => http://example.com/images/user_adv/147.jpg
)
[small_image] => Array
(
[0] => http://example.com/images/user_adv/small/154.jpg
[1] => http://example.com/images/user_adv/small/144.jpg
[2] => http://example.com/images/user_adv/small/147.jpg
)
顺便说一句,如果我替换:
foreach ($json['data'] as $fields) {
带
foreach ($json['data'][0] as $fields) {
我将链接图片作为输出,因此我需要将它们合并为一个输出
foreach ($json['data'] as $fields) {
foreach ($json['data'][0] as $fields2) {
编辑:
这里是输出
编辑2:
我希望输出类似
答案 0 :(得分:0)
您可以创建一个函数来确保这些嵌套数组变得平坦。您可以为此创建实用程序功能,如下所示:
function array_flatten ($nonFlat) {
$flat = array();
foreach (new RecursiveIteratorIterator(
new RecursiveArrayIterator($nonFlat)) as $k=>$v) {
$flat[$k] = $v;
}
return $flat;
}
并称之为:
$fp = fopen("output.csv","w");
foreach ($json['data'] as $fields) {
fputcsv($fp, array_flatten($fields));
}
fclose($fp);