类stdClass的对象无法在laravel中转换为字符串

时间:2017-05-24 20:31:19

标签: php mysql laravel

我尝试使用sql查询编写一个文本文件,但它显示错误说:

  

类stdClass的对象无法转换为字符串

这是我的代码:

$myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
$ss=DB::select("SELECT  commercial_library FROM tbl_schedule");

$stringData = implode(', ',$ss);
fwrite($myfile, $stringData);
fclose($myfile);

3 个答案:

答案 0 :(得分:1)

Implode将数组转换为字符串。我认为$ss在你的情况下是一个数组,它看起来像一个对象。这可能是您收到此错误的原因。

答案 1 :(得分:1)

将对象转换为数组,然后使用implode。 Implode将第一个参数作为数组。

<?php
$myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
$ss=DB::select("SELECT  commercial_library FROM tbl_schedule");
$ss = (array) $ss;
$stringData = implode(', ', $ss);
fwrite($myfile, $stringData);
fclose($myfile);

答案 2 :(得分:1)

Object of class stdClass could not be converted to string转换为数组后,您得到$ss因为您还有一个对象数组。我尝试使用递归函数解决您的问题。我有不同级别的stdClasses和值。请将$ss的定义替换为您的查询并尝试使用我的代码。

$myfile = fopen("newfile.txt", "w") or die("Unable to open file!");

$ss = new stdClass();
$ss->a = new stdClass();
$ss->a->a = new stdClass();
$ss->a->b = new stdClass();
$ss->b = new stdClass();

$ss->a->a->a = "!";
$ss->a->a->b = "T";
$ss->a->b->a = "E";
$ss->a->b->b = "X";
$ss->b->a = "T";
$ss->b->c = 1;

$string = recursive($ss, "");

fwrite($myfile, $string);
fclose($myfile);

function recursive($objects, $string) {
    foreach($objects as $object) {
        if ($object instanceof stdClass) {
            $string = recursive((array) $object, $string);
        } else {
            $string .= implode(', ', (array) $object); //my example is to concatenate
        }
    }
    return $string;
}