我有一个JSON文件,我需要使用PHP将其转换为CSV。但是,只有JSON文件中的某些记录才应该根据它们是否符合某些条件进行转换。如果JSON数据是金融交易,则只有那些符合某些商家ID的交易才应该进行转换。
我已经在PHP中将JSON数据提取到一个数组中,但不确定如何条件匹配记录,然后将其转换为csv。
<?php
$raw_data = file_get_contents('transactions.json');
$decoded_json = json_decode($raw_data, true);
foreach($decoded_json as $row) {
foreach($row['payee'] as $k) {
print_r($row);
echo "<pre>";
echo $k;
echo "</pre>";
}
}
$file = fopen("output.csv", "a");
foreach($decoded_json as $row){
fputcsv($file, $row);
}
fclose($file);
?>
JSON文件的示例,所以我只需要匹配[并转换为csv]与“merchantId”匹配的交易:“一一四四”。
{
"id": "xxxxxxxxxxxxxxxxxx",
"amount": 1099,
"currency": "GBP",
"payee": {
"merchantId": "1144"
},
"payer": {
"accountNo": "xxxxxxxxxxxxxxxx"
},
"created_date_time": "2021-04-06T16:46:02+01:00",
"txn_lifecycle_status": "AUTHORISED"
},
{
1条答案
按热度按时间des4xlb01#
您可以通过一些字段过滤解码的json,这些字段排除了不需要的“merchant id”,您可以使用fputcsv()将整个过滤后的数据写入内存,然后写入文件系统
这是一个例子,我不知道你的JSON结构
我已根据提供的新信息调整了示例