数组到字符串的转换laravel 7

问题描述 投票:0回答:2

我需要获取数组中没有字符串的值。这将是字段名称:

 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.

php laravel eloquent laravel-7
2个回答
0
投票

问题1:通过数组元素调用对象属性

发生错误消息是因为$getFieldName作为变量,对象调用不带[0]的变量,需要用大括号将$getFieldName[0]包装:

$items->{$getFieldName[0]};

问题2:从分页器处收集:

您正在将paginate应用于查询生成器,结果将是Illuminate\Pagination\LengthAwarePaginator对象。

如果要在内部放入客户对象。您可以对getCollection()使用$table方法:

   foreach($table->getCollection() as $items){
        $a[] = $items->${getFieldName[0]};
   }

0
投票

[如果尝试使用键CUST_CITY仅检索CUST_NAME的列表,则可以使用pluck()方法:

$array = DB::table("dummy_db.customer")
    ->take(10)
    ->pluck('CUST_CITY','CUST_NAME');


0
投票

如果需要这两个字段,可以将其放在选择中。

$table = DB::table("dummy_db.customer")->select('CUST_NAME','CUST_CITY')->paginate(10);


   foreach($table as $items){
        $a[] = $items->CUST_NAME;
   }
© www.soinside.com 2019 - 2024. All rights reserved.