-1
0 => array[
"id" => "94e568e2-e5ef-4565-b9d1"
"code" => "8899014500001"                                                        
"name" => "John"
"age" => "24" ]

I'm trying to convert an array of users into a CSV file. And i set the array of the key that I want to export.

 $fields = ['id', 'name'];

How can I fputcsv in foreach loop return only user id and name from $fields array ?

 foreach ($user as $item) {
      fputcsv($output, $item);
 }
Jestzy
  • 1
  • 1

1 Answers1

0

Make an array containing only the fields you want using the $fields array to decide what to place in the output

$fields = ['id', 'name'];

foreach ($users as $user) {
    $out = [];
    foreach ( $fields as $field){
        $out[$field] = $user[$field];
    }
    fputcsv($output, $out);
}
RiggsFolly
  • 93,638
  • 21
  • 103
  • 149