0

I have to make a csv file that work in this way:

Row 1 --> Text Data 
Row 2 --> Person Information
Row 3 --> Products information 

The Row1 and Row2 are done, I have alrady wirte the code correctly.

The Row3 is a problem becasue need give me back a row for every products, with all their data.

How I can write the code in the way? At moment I havw write this, but the row3 is empty.

$list = array (
    array ('Order id', 'Billing Name' , 'Product Title', 'Total Price' ),
    array ($order->id, $order->firstname, '', ''),   
    $listProd = array(),
  );

  $listProd = array();
  foreach ($order->products as $product) {
    $listProd = array (
        $order->id,
        '',
        $product->title,
        $cart->renderPriceAndCurrency($product->pad_price),
    );
  }

  $local_file = fopen('php://temp', 'r+');
    foreach ($list as $row) {
      fputcsv($local_file, $row);
  }

  rewind($local_file);

thank you.

1 Answer 1

1
$list = array (
    array ('Order id', 'Billing Name' , 'Product Title', 'Total Price' ),
    array ($order->id, $order->firstname, '', ''),   
    $listProd = array(), // this does __nothing__ except adding empty array to `$list`
);

Replace it with:

$list = array (
    array ('Order id', 'Billing Name' , 'Product Title', 'Total Price' ),
    array ($order->id, $order->firstname, '', ''),   
);
foreach ($order->products as $product) {
    $list[] = array (
        $order->id,
        '',
        $product->title,
        $cart->renderPriceAndCurrency($product->pad_price),
    );
}

Here you add every product item to the end of $list array.

Sign up to request clarification or add additional context in comments.

4 Comments

Easy! thenk you @u_mulder I went in confusion with all these arrays and foreach!
Do you know way, in the CSV file I see all products duplicated? If I put 2 products I see 2 time the same row and if I put 3 products I see 3 time the same row.
I don't know why items are duplicated. Try to debug your code. Output $list array - if there're duplicates - then it's connected with your foreach.
I find the error, doesn't in the foreach. was in the $local_file foreach. Your code work so well! thank you again.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.