将JSON数据有条件提取到CSV文件

91zkwejq  于 2023-03-15  发布在  其他
关注(0)|答案(1)|浏览(100)

我有一个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"
},
{
des4xlb0

des4xlb01#

您可以通过一些字段过滤解码的json,这些字段排除了不需要的“merchant id”,您可以使用fputcsv()将整个过滤后的数据写入内存,然后写入文件系统
这是一个例子,我不知道你的JSON结构

我已根据提供的新信息调整了示例

<?php

$idsWanted = ['1144', '1145', '1146'];

$raw_data = file_get_contents('transactions.json');
$decoded_json = json_decode($raw_data, true);

$memoryFile = fopen('php://temp/maxmemory:'. (5*1024*1024), 'r+');

foreach ($decoded_json as $rowN => &$row)
{
    if (in_array(($row['payee']['merchantId'], $idsWanted)  // take only wanted
    {
        foreach ($row as $k => $v) // 'flatten' keys
            if (is_array($v)) 
            {
                $row[$k . '_' . array_key_first($v)] = reset($v); 
                unset($row[$k]);
            }
        
        if ($rowN === 0)
            fputcsv($memoryFile, array_keys($row));  // CSV headers
        
        fputcsv($memoryFile, $row);
    }
}

rewind($memoryFile);

file_put_contents('output.csv', stream_get_contents($memoryFile));  

fclose($memoryFile);

相关问题