我需要获取数组中没有字符串的值。这将是字段名称:
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.
发生错误消息是因为$getFieldName
作为变量,对象调用不带[0]
的变量,需要用大括号将$getFieldName[0]
包装:
$items->{$getFieldName[0]};
您正在将paginate
应用于查询生成器,结果将是Illuminate\Pagination\LengthAwarePaginator
对象。
如果要在内部放入客户对象。您可以对getCollection()
使用$table
方法:
foreach($table->getCollection() as $items){
$a[] = $items->${getFieldName[0]};
}
[如果尝试使用键CUST_CITY
仅检索CUST_NAME
的列表,则可以使用pluck()
方法:
$array = DB::table("dummy_db.customer")
->take(10)
->pluck('CUST_CITY','CUST_NAME');
如果需要这两个字段,可以将其放在选择中。
$table = DB::table("dummy_db.customer")->select('CUST_NAME','CUST_CITY')->paginate(10);
foreach($table as $items){
$a[] = $items->CUST_NAME;
}