return inside foreach php and laravel

爱⌒轻易说出口 提交于 2019-12-30 11:08:27

问题


I trying to return data every time inside the foreach() but i keep on getting the data on the first iteration of the loop here is my code

  for ($i = 0 ;$i<4;$i++)
    {
        var_dump($i);
        $publisher = Publisher::find($results[$i]->publisherId);
        //pr($publisher);
        $channels =$publisher->channels()->get() ;
        pr($channels[0]);
        $data = ReviveAgent::getPublisherDailyStatistics($channels[0],$start,$end);
        pr($data);
        return Response::json($data);


    }

on the var_dump($i); It only shows data for the first 0 only.So how can i return the data also for 1,2,3

here is my output when pr($data) for var_dump($i) = 1

            array (

   0 => 
  array (
'impressions' => 1867,
'clicks' => 14,
'requests' => 44,
'revenue' => 2.79,
'day' => 
stdClass::__set_state(array(
   'scalar' => '20150518T00:00:00',
   'timestamp' => 1431907200,
   'xmlrpc_type' => 'datetime',
    )),
   ),
 1 => 
 array (
'impressions' => 2197,
'clicks' => 17,
'requests' => 382,
'revenue' => 19.829999999999998,
'day' => 
stdClass::__set_state(array(
   'scalar' => '20150519T00:00:00',
   'timestamp' => 1431993600,
   'xmlrpc_type' => 'datetime',
   )),
  ),
  2 => 
    array (
 'impressions' => 5484,
'clicks' => 3,
'requests' => 3680,
'revenue' => 6.7300000000000004,
'day' => 
stdClass::__set_state(array(
   'scalar' => '20150520T00:00:00',
   'timestamp' => 1432080000,
   'xmlrpc_type' => 'datetime',
 )),
 ),
 3 => 
 array (
'impressions' => 6909,
'clicks' => 105,
'requests' => 5141,
'revenue' => 378.88499999999999,
'day' => 
stdClass::__set_state(array(
   'scalar' => '20150521T00:00:00',
   'timestamp' => 1432166400,
   'xmlrpc_type' => 'datetime',
     )),
    ),

回答1:


The return operator implicitly ends the current execution scope. The context of your usage is not given, but you could put your $data into an array prior to JSON encoding and returning it. It might look something like this:

$data = array();
for ($i = 0; $i < 4; $i++) {
    ...
    $record = ReviveAgent::getPublisherDailyStatistics($channels[0], $start, $end));
    pr($record);
    $data[] = $record;
}
return Response::json($data);


来源:https://stackoverflow.com/questions/30516904/return-inside-foreach-php-and-laravel

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!