doudou3716 2016-07-05 03:36 采纳率: 100%
浏览 27

错误 - 无法遍历已关闭的生成器

I ran into this error today and sort of lost as to how to deal with it.

My app is grabbing data from an API and with that data, I query my database, get required data, create new value and send it back to API to update.

I have done some googling but still getting the hang of MVC and laravel, nothing I have read I could get to work with my code:

// Create Connection
$client = new Name\App(
      env('DOMAIN'),
      env('API_KEY'),
      env('PASSWORD'),
      env('SECRET')
    );

    //Get data from API
    $something = $client->getSomething('something');

    // Make empty Array
    $arr = [];

    // loop through data from API and create array of required data
    foreach ($something as $thing) {
      $arr[] = array('colors' => $thing->color);
    }

    // query database for values found from API array
    $eg = DB::table('table')
    ->select('eg','size', 'weight')
    ->whereIn('eg', $arr) // whereIn to query array
    ->get();

    // create another blank array
    $data = [];

    // loop the above query 
    foreach ($eg as $type) {

      // create json value to send back to api 
      // and update
      $data[] = [
        'mindfull' => [
          'this' =>  $type->en,
          'that' =>  $type->tva
        ]
      ];
    }

    // update API (this gives me the traverse generator error)
    foreach ($something as $again) {
      $client->put('link/' . $again->id, $data);
    }
  }

Any Ideas would be helpful.

  • 写回答

1条回答 默认 最新

  • dpkiubcc265650 2016-07-05 13:35
    关注

    This adds another iteration to your algorithm, but I guess this has to work:

    Replace

    //Get data from API
    $something = $client->getSomething('something');
    

    with

    //Get data from API
    $something = []
    foreach ($client->getSomething('something') as $thing)
       $something []= $thing;
    

    This way, the original generator is iterated only once. After that you have your array with the data.

    评论

报告相同问题?

悬赏问题

  • ¥15 yolov8边框坐标
  • ¥15 matlab中使用gurobi时报错
  • ¥15 WPF 大屏看板表格背景图片设置
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真