PHP使用foreach()向元素添加元素

时间:2017-06-05 12:47:28

标签: php arrays

如何使用foreach循环向元素添加元素?

    $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);
    }

好像我的问题位于$list .=。如何在这个数组中插入另一个数组,所以我可以从数组中生成一个.CSV文件?

1 个答案:

答案 0 :(得分:1)

.=用于连接字符串 - 而不是数组。

你只需要使用;

$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,
    ];

这会将您的新数组添加到$list数组的末尾。

您也可以使用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,
]);