JSON PHP 中的数组导出为 CSV
JSON Array Export to CSV in PHP
我正在尝试导出为 csv,JSON 格式如下:
</p>
<pre><code>$json_file2{
"errors":
{
"code":0,
"text":""
},
"results":
{
"resultado":
[
{
"referencia":"00000",
"cantidad":"24",
"cantidad_proveedor":null,
"delivery_time":"delivery time 2 days"
},
{
"referencia":"00001",
"cantidad":"24",
"cantidad_proveedor":"48",
"delivery_time":""
},
{
"referencia":"00098_1",
"cantidad":"96",
"cantidad_proveedor":null,
"delivery_time":"delivery time 4 days"
}
]
}
}
我需要导出到 csv
</p>
<pre><code>"referencia":"00000",
"cantidad":"24",
"cantidad_proveedor":null,
"delivery_time":"delivery time 2 days"
采用这种格式:
</p>
<pre><code>"00000","24",null,"delivery time 2 days"
"00001","24","48",""
"00098_1","96",null,"delivery time 4 days"
......
我努力边学边做
</p>
<pre><code>$decoded = json_decode($json_file2);
$comments = $decoded->data[0]->results->resultado;
$fp = fopen('stock2.csv', 'w');
foreach($comments as $comment){
fputcsv($fp,$comment);
}
但它总是给我错误 foreach:
警告:为 foreach()
提供的参数无效
我哪里做错了?
坦克
您必须将数组传递给 fputcsv。使用此代码:
fputcsv($fp,(数组)$comment);
$json_file2 中没有数据数组字段。
您必须改用 $decoded->results->resultado 。并将 $comment 转换为 array 正如 Brian 所说。
最终代码如下所示:
$decoded = json_decode($json_file2);
$comments = $decoded->results->resultado;
$fp = fopen('stock2.csv', 'w');
foreach($comments as $comment) {
fputcsv($fp, (array)$comment);
}
有了这个改变,你会得到类似的东西:
00000,24,,"delivery time 2 days"
00001,24,48,
00098_1,96,,"delivery time 4 days"
也许您应该编写您自己的 fputcsv 函数来获得您想要的结果,使用 null 和带引号的数字。
我正在尝试导出为 csv,JSON 格式如下:
</p>
<pre><code>$json_file2{
"errors":
{
"code":0,
"text":""
},
"results":
{
"resultado":
[
{
"referencia":"00000",
"cantidad":"24",
"cantidad_proveedor":null,
"delivery_time":"delivery time 2 days"
},
{
"referencia":"00001",
"cantidad":"24",
"cantidad_proveedor":"48",
"delivery_time":""
},
{
"referencia":"00098_1",
"cantidad":"96",
"cantidad_proveedor":null,
"delivery_time":"delivery time 4 days"
}
]
}
}
我需要导出到 csv
</p>
<pre><code>"referencia":"00000",
"cantidad":"24",
"cantidad_proveedor":null,
"delivery_time":"delivery time 2 days"
采用这种格式:
</p>
<pre><code>"00000","24",null,"delivery time 2 days"
"00001","24","48",""
"00098_1","96",null,"delivery time 4 days"
......
我努力边学边做
</p>
<pre><code>$decoded = json_decode($json_file2);
$comments = $decoded->data[0]->results->resultado;
$fp = fopen('stock2.csv', 'w');
foreach($comments as $comment){
fputcsv($fp,$comment);
}
但它总是给我错误 foreach: 警告:为 foreach()
提供的参数无效我哪里做错了? 坦克
您必须将数组传递给 fputcsv。使用此代码:
fputcsv($fp,(数组)$comment);
$json_file2 中没有数据数组字段。 您必须改用 $decoded->results->resultado 。并将 $comment 转换为 array 正如 Brian 所说。
最终代码如下所示:
$decoded = json_decode($json_file2);
$comments = $decoded->results->resultado;
$fp = fopen('stock2.csv', 'w');
foreach($comments as $comment) {
fputcsv($fp, (array)$comment);
}
有了这个改变,你会得到类似的东西:
00000,24,,"delivery time 2 days"
00001,24,48,
00098_1,96,,"delivery time 4 days"
也许您应该编写您自己的 fputcsv 函数来获得您想要的结果,使用 null 和带引号的数字。