数组到字符串的转换laravel 7
Array to string conversion laravel 7
我需要获取数组中没有字符串的值。这将是字段名称:
static function showCust(){
$table = DB::table("dummy_db.customer")->select("*")->paginate(10);
$getFieldName = ["CUST_NAME", "CUST_CITY"];
foreach($table as $items){
$a[] = $items->$getFieldName[0];
}
dd($a);
}
但结果:
ErrorException
Array to string conversion.
如果您尝试仅使用键 CUST_NAME
检索 CUST_CITY
的列表,您可以使用 pluck()
方法:
$array = DB::table("dummy_db.customer")
->take(10)
->pluck('CUST_CITY','CUST_NAME');
问题 1:通过数组
的元素调用对象 属性
出现错误消息是因为$getFieldName
作为一个变量,对象调用没有[0]
的变量,你需要用大括号包裹$getFieldName[0]
:
$items->{$getFieldName[0]};
问题 2:从分页器获取集合:
您正在将 paginate
应用于查询生成器,结果将是 Illuminate\Pagination\LengthAwarePaginator
对象。
如果要获取里面的客户对象。您可以使用 getCollection()
方法 $table
:
foreach($table->getCollection() as $items){
$a[] = $items->${getFieldName[0]};
}
我需要获取数组中没有字符串的值。这将是字段名称:
static function showCust(){
$table = DB::table("dummy_db.customer")->select("*")->paginate(10);
$getFieldName = ["CUST_NAME", "CUST_CITY"];
foreach($table as $items){
$a[] = $items->$getFieldName[0];
}
dd($a);
}
但结果:
ErrorException
Array to string conversion.
如果您尝试仅使用键 CUST_NAME
检索 CUST_CITY
的列表,您可以使用 pluck()
方法:
$array = DB::table("dummy_db.customer")
->take(10)
->pluck('CUST_CITY','CUST_NAME');
问题 1:通过数组
的元素调用对象 属性出现错误消息是因为$getFieldName
作为一个变量,对象调用没有[0]
的变量,你需要用大括号包裹$getFieldName[0]
:
$items->{$getFieldName[0]};
问题 2:从分页器获取集合:
您正在将 paginate
应用于查询生成器,结果将是 Illuminate\Pagination\LengthAwarePaginator
对象。
如果要获取里面的客户对象。您可以使用 getCollection()
方法 $table
:
foreach($table->getCollection() as $items){
$a[] = $items->${getFieldName[0]};
}