不能将stdClass类型的对象用作数组 [英] php - fputcsv Cannot use object of type stdClass as array

查看:53
本文介绍了不能将stdClass类型的对象用作数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我使用get方法时,我使用post方法使用带有 fputcsv 的php下载csv,但是它在使用post时给我错误,无法将stdClass用作数组,人们提到使用 json_decode ,但我不确定是否要放置它,

I use post method to download csv using php with fputcsv when i using get method it works, but when using post it give me error, cannot use stdClass as array, people mention to use json_decode but i'm not sure wher to place it,

我用laravel

代码:

public function csv (Request $request) {

    $storage_path = storage_path();

    $from = date($request->from_date);
    $to = date($request->to_date);

    $table = DB::table('registrations')->whereBetween('created_at', [$from, $to])->get();



    $filename = "data.csv";
    $handle = fopen('php://output', 'w+');

    fputcsv($handle, array('No', 'Nama', 'Nomor Telepon', 'Email', 'Tempat Tinggal',
        'Bank', 'Kartu Kredit', 'Rumah', 'Mobil', 'Luar Negeri', 'Penghasilan'));

    foreach($table as $row) {
            fputcsv($handle, array( $row['id'], $row['name'], $row['phonenumber'], $row['email'],
                            $row['umur'], $row['tempattinggal'],
                            $row['bank'], $row['kartukredit'], $row['rumah'],
                            $row['keluarnegeri'], $row['penghasilan'] ));
    }

    fclose($handle);

    $headers = array(
            'Content-Type' => 'text/csv',
    );

    return Response::download($filename, 'data.csv', $headers);
}

错误恰好发生在foreach上,当我删除for时,可以下载csv,但是格式不正确

the error happen to be on foreach,when i remove the for each , i can donwload the csv, but in badly format

推荐答案

我认为您的代码存在的问题是,从数据库中获取记录时,它们将作为对象返回,而您试图像使用它一样使用该对象是一个数组.

I think the issue with your code is that when fetching the records from the database they are being returned as object and you are trying to use that object as if it was an array.

您有2个解决方案,解决方案1是最有效的:

You have 2 solutions, solution 1 is the most efficient:

解决方案1:使用变量 $ row 作为对象而不是数组

Solution 1: Use the variable $row as an object instead of an array

foreach($table as $row) {
    fputcsv($handle, array( $row->id, $row->name, $row->phonenumber, $row->email,$row->umur, $row->tempattinggal,$row->bank, $row->kartukredit, $row->rumah,$row->keluarnegeri, $row->penghasilan ));
}

解决方案2:为每个循环将 $ row 转换为数组

Solution 2: Convert the $row to an array for every loop

foreach($table as $row) {
    $row = json_decode(json_encode($row), True);
    //Or $row = (array)$row;
    fputcsv($handle, array( $row['id'], $row['name'], $row['phonenumber'], $row['email'],$row['umur'], $row['tempattinggal'],$row['bank'], $row['kartukredit'], $row['rumah'],$row['keluarnegeri'], $row['penghasilan'] ));
}

这篇关于不能将stdClass类型的对象用作数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆