2016-07-24 32 views
0

我有一個對象,所以我想知道怎樣才能從object.Object例如數據低於怎樣才能從對象數據在PHP

return $response= PowerConsumption::groupBY('device_id') 
      ->selectRaw('round(sum(unit),4) as yAxis,device_id') 
      ->where('created_at',Carbon::now())->paginate(1); 

給出所以這雄辯查詢創建給定的數據,但我需要current_page,請不要更改我的查詢。只有幫助我找出此響應的current_page值。

{ 
total: 2, 
per_page: 1, 
current_page: 1, 
last_page: 2, 
next_page_url: "http://localhost:8000/graph/monthly/user_id/2?page=2", 
prev_page_url: null, 
from: 1, 
to: 1, 
data: [ 
{ 
yAxis: 222.8572, 
device_id: 1 
} 
] 
} 

該數據存儲在$ response變量中,我只需要current_page和last_page,我該如何獲得。 我想要這個樣

$response['current_page']; //it's return null 
$response->current_page; //it's return error like 
Undefined property: Illuminate\Pagination\LengthAwarePaginator::$current_page 

請幫我在獲取數據

+0

您的'$ response'不是您認爲的那樣。它是['LengthAwarePaginator'](https://laravel.com/api/5.0/Illuminate/Pagination/LengthAwarePaginator.html)。也許它包含一個響應對象? – Chris

+0

你能顯示'var_dump($ response);'? – RomanPerekhrest

+0

$ resonse-> current_page; <====你缺少字符[p] –

回答

0

只需使用PHP對象的訪問方式就可以得到從你的對象你想要的任何數據,如下圖所示......但是,請注意你在代碼$response->current_page中有一個Typo,而不是$resonse->current_page;,因爲@QuỳnhNguyễn在他上面的評論中指出。

<?php 

    /* 
    YOUR $response, AS A PHP OBJECT, COULD BE REPRESENTED WITH THE OBJECT VARIABLE; $response BELOW 
    { 
    total: 2, 
    per_page: 1, 
    current_page: 1, 
    last_page: 2, 
    next_page_url: "http://localhost:8000/user/user_id/2?page=2", 
    prev_page_url: null, 
    from: 1, 
    to: 1, 
    } 
    */ 

    $response     = new stdClass(); 
    $response->total   = 2; 
    $response->per_page  = 1; 
    $response->current_page = 1; 
    $response->last_page  = 2; 
    $response->next_page_url = "http://localhost:8000/user/user_id/2?page=2"; 
    $response->next_page_url = null; 
    $response->from   = 1; 
    $response->to    = 1; 

    // NOW TO GET THE current_page, you could do: 
    $response->current_page; 
很可能您正在使用Laravel ......如果是這樣,這是你的控制器可能是什麼樣子:
<?php 

    namespace App\Http\Controllers; 

    use Illuminate\Http\Request; 

    use App\Http\Requests; 

    class PowerController extends Controller{ 

     public function power(){ 
      $response = PowerConsumption::groupBY('device_id') 
             ->selectRaw('round(sum(unit),4) as yAxis,device_id') 
             ->where('created_at',Carbon::now())->paginate(1); 
      // YOU SHOULD RETURN VIEW INSIDE YOUR METHOD 
      // AND PASS THE $response AS ARGUMENT... 

      return view('your_view_name', compact($response));    
     } 
    } 
現在,在您的視圖;您應該可以像訪問任何通常聲明的變量一樣訪問您的數據:
//your_view_name.blade.php 
{{ $current_page }} 
{{ $next_page_url }} 
{{ $prev_page_url }} 
{{ $total }} 
+0

你沒有完成你的答案。 –

+0

@MarkoMackic對不起...意外刪除它發佈之前...不得不重新做它:-( – Poiz

+0

我是新的PHP所以幫助我的例子.. – User101