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

问题描述 投票:0回答:1

我有一个 JSON 文件,我需要使用 PHP 将其转换为 CSV。但是,只有 JSON 文件中的某些记录应根据它们是否符合某些条件进行转换。在 JSON 数据是金融交易的情况下,只有那些与特定商家 ID 匹配的交易才应该被转换。

我已经将 JSON 数据提取到 PHP 中的数组中,但不确定如何条件匹配记录,然后应将其转换为 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”的交易:“1144”。

      {
    "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"
},
{
php json csv
1个回答
0
投票

您可以通过排除不需要的“商家 ID”的某些字段来过滤解码后的 json,您可以使用 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);    
© www.soinside.com 2019 - 2024. All rights reserved.