1

I have associative array '$reportData' having objects of 'report_Modal'.

Attributes of 'report_Modal' are:

private $unique_product_name;
private $min_price_quote;
private $max_price_quote;
private $mean_price_quote;
private $price_variation;
private $savings_potential;
private $vendor_name_OLP;

All setters and getters exists for all private attributes.

I want to write all objects to CSV with header like:

Product Name,Min Price,Max Price,Mean Price,Price Variation,Savings Potential,
Vendor Name OLP
Memory Card,110,200,142.5,1.03,0.23,Kingston
USB,125,230,171.5,1.02,0.27,Sandisk

P.S: I am new to php

Data k
  • 13
  • 1
  • 4

2 Answers2

1

You need a way to access a list of private properties dynamically. Here's an example of a function that does that:

function toArray($report_modal, $properties) {
    return array_map(function($property) use ($report_modal) {
        return $report_modal->{'get_'.$property}();
        // modify according to how your methods are named
    }, $properties);
}

Then if you define the list of properties you want to get

$properties = [
    'unique_product_name',
    'min_price_quote',
    'max_price_quote',
    'mean_price_quote',
    'price_variation',
    'savings_potential',
    'vendor_name_OLP',
];

You can iterate your array of objects, convert them to arrays, and and output them to CSV.

foreach ($reports as $report) {
    fputcsv('outputfile.csv', toArray($report, $properties));
}

If you can modify the class, you could also implement a toArray method internally if you like.

Don't Panic
  • 41,125
  • 10
  • 61
  • 80
0

Just convert your array of objects into array of arrays, then use the function from this post or this

<?php
$header = ['Product Name','Min Price','Max Price','Mean Price','Price Variation','Savings Potential','Vendor Name OLP'];
$finalArray = [$header];
foreach ($ascArray as $obj){
    $a = [];
    $a[] = $obj->get_unique_product_name();
    $a[] = $obj->get_min_price_quote();
    $a[] = $obj->get_max_price_quote();
    $a[] = $obj->get_mean_price_quote();
    $a[] = $obj->get_price_variation();
    $a[] = $obj->get_savings_potential();
    $a[] = $obj->get_vendor_name_OLP();

    $finalArray[] = $a;    
}
Accountant م
  • 6,975
  • 3
  • 41
  • 61