0

How to add elements to the array using the foreach loop?

    $list = [
        ['User-ID', 'Payout-ID', 'Amount', 'Withdraw address', 'Date'],
    ];

    //generate CSV
    foreach ($open_payouts as $open_payout) {
        $list .= [
            (string)$open_payout->user_id,
            (string)$open_payout->id,
            (string)number_format($open_payout->amount / 100000000, 8, '.', ''),
            (string)$open_payout->user->withdraw_address,
            (string)$open_payout->created_at,
        ];
    }

    $fp = fopen(app_path() . '/CSV/file.csv', 'w');
    //write whole list
    foreach ($list as $fields) {
        fputcsv($fp, $fields);
    }

It seems like my problem is located at $list .=. How to insert another array into this array, so I can generate a .CSV file from the arrays?

2
  • 2
    $list[] = [x, y, z, ...]; which is shorthand for array_push() Commented Jun 5, 2017 at 12:49
  • 1
    To add elements to an array, its $list[] =. Using $list .= is for string concating. Commented Jun 5, 2017 at 12:49

1 Answer 1

1

.= is used to concatenate strings - not arrays.

You simply need to use;

$list[] = [
        (string)$open_payout->user_id,
        (string)$open_payout->id,
        (string)number_format($open_payout->amount / 100000000, 8, '.', ''),
        (string)$open_payout->user->withdraw_address,
        (string)$open_payout->created_at,
    ];

That will add your new array onto the end of your $list array.

You could also use array_push();

array_push($list, [
    (string)$open_payout->user_id,
    (string)$open_payout->id,
    (string)number_format($open_payout->amount / 100000000, 8, '.', ''),
    (string)$open_payout->user->withdraw_address,
    (string)$open_payout->created_at,
]);
Sign up to request clarification or add additional context in comments.

Comments

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.