laravel 查询数据toArray内层无法转换的问题
生活随笔
收集整理的這篇文章主要介紹了
laravel 查询数据toArray内层无法转换的问题
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
語法:get_object_var($object),返回一個數組。獲取$object對象中的屬性,組成一個數組
<?php
class person{
public $name="王美人";
public $age = 25;
public $birth;
}
$p = new person();
print_r(get_object_vars($p));
?>
輸出結果:
Array ( [name] => 王美人 [age] => 25 [birth] => )
在laravel數據庫查詢中使用toArray()方法外層已經轉化成了數組,但是內層依然是對象的問題。
array (size=1)
0 =>
object(stdClass)[1804]
public 'id' => int 17
public 'ip' => string '192.168.0.60' (length=12)
public 'access_time' => int 1615625654
public 'access_count' => int 1
public 'last_time' => int 1615625672
在vendorlaravelframeworksrcIlluminateSupportCollection.php中增加方法getArrayList()
public function toArray()
{
return array_map(function ($value) {
return $value instanceof Arrayable ? $value->toArray() : $value;
}, $this->items);
}
/*增加方法*/
public function getArrayList(){
return array_map('get_object_vars', $this->items);
}
查詢時使用:
DB::table('api_log')->select('id','ip','access_time','access_count','last_time')->where('ip',$logInfo['ip'])->orderBy('id','desc')->limit(1)->get()->getArrayList()[0];
顯示結果:
array (size=5) 'id' => int 17 'ip' => string '192.168.0.60' (length=12) 'access_time' => int 1615625654 'access_count' => int 0 'last_time' => int 1615625654
Array ( [name] => 王美人 [age] => 25 [birth] => )
總結
以上是生活随笔為你收集整理的laravel 查询数据toArray内层无法转换的问题的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: php java 单点登录_php实现多
- 下一篇: python初学篇笔记_Python学习