Conditional extraction of JSON data to CSV file

I have a JSON file which I need to convert to CSV using PHP. However, only certain records from the JSON file should be converted based on whether they match certain conditions. In the case the JSON data is financial transactions, and only those transactions which match certain merchant id’s should be converted.

I have extracted the JSON data into an array in PHP but not sure how to condition match the records which should then be converted to 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);
?>

You can use an if statement to check if a record matches the conditions you want before converting it to CSV.

Here’s an example of how you might do this:

<?php

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

// Define an array of desired merchant ids
$desired_merchant_ids = [123, 456, 789];

$file = fopen("output.csv", "a");

foreach($decoded_json as $row) {
    // Check if the merchant id of the transaction is in the desired merchant ids array
    if (in_array($row['merchant_id'], $desired_merchant_ids)) {
        fputcsv($file, $row);
    }
}

fclose($file);
?>

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.