【问题标题】:Laravel, array is undefined?Laravel,数组未定义?
【发布时间】:2017-07-31 19:45:34
【问题描述】:

我有这样的功能:

    public function handle()
    {
        News::truncate();
        $client = new Client();
        $crawler = $client->request('GET', 'features');
        $crawler->filter('div[id=content]>.homefeature')->each(function ($node, $key) {
        $title = $node->filter('.plain')->text();
        $datepublished = $node->filter('.dateonline')->text();
        $description = $node->filter('.teaser-link')->text();
        $link = $node->filter('a')->link();
        $link_r = $link->getUri();
        if ($image = $node->filter('img')->count () > 0) {
        $title = $node->filter('.plain')->text();
        $datepublished = $node->filter('.dateonline')->text();
        $description = $node->filter('.teaser-link')->text();
        $link = $node->filter('a')->link();
        $link_r = $link->getUri();
        $image = $node->filter('img')->image();
        $image_s = $image->getUri();
        $image_s = preg_replace("/thumb_/", "", $image_s);
        $filename = basename($image_s);
        $image_path = ('news-gallery/' . $filename);
        Image::make($image_s)->save(public_path('news-gallery/' . $filename));
        $id = 1+ $key + 1;
        $news = News::where('id', $id)->first();
        // if news is null
        if (!$news) {
            $news = new News();
        }
        $news->title = $title;
        $news->datepublished = $datepublished;
        $news->description = $description;
        $news->link = $link_r;
        $news->image = $image_path;
        $news->save();
        $this->info('Main article ' .$title. ' done succesfully');
    });
    $crawler->filter('div[id=content]>.teaser-50')->each(function ($node, $key) {
        $title = $node->filter('.plain')->text();
        $datepublished = $node->filter('.dateonline')->text();
        $description = $node->filter('.teaser-link')->text();
        $link = $node->filter('a')->link();
        $link_r = $link->getUri();
        $title = $node->filter('.plain')->text();
        $datepublished = $node->filter('.dateonline')->text();
        $description = $node->filter('.teaser-link')->text();
        $link = $node->filter('a')->link();
        $link_r = $link->getUri();
        $image = $node->filter('img')->image();
        $image_s = $image->getUri();
        $image_s = preg_replace("/thumb_/", "", $image_s);
        $filename = basename($image_s);
        $image_path = ('news-gallery/' . $filename);
        Image::make($image_s)->save(public_path('news-gallery/' . $filename));
        //$id = 1+ $key + 1;
        $newsArray[] = [
            'title' => $title,
            'datepublished' => $datepublished,
            'description' => $description,
            'link' => $link_r,
            'image' => $image_path,
            ];       
        $this->info('Scraping done for ' .$title. ' succesfully');
    });
    print_r($newsArray);
    //$news = News::insert($newsArray);
    }
}

所以我试图在保存之前将所有内容放入一个数组中,但是我收到一个错误,说 $newsArray 未定义?如果我把 print_r 放在函数里面,就在它下面我得到一个输出。如何解决?我想要做的是像现在一样循环遍历每个结果,将其插入到数组中,然后将其批量插入到数据库中

//示例:

 public function handle()
    {
    /* Clear table, set array of id's, and get today's date */
    Film::truncate();
    $arrayOfCinemaIds = [10565,7311,9434];
    $startdate = strtotime("today");
    $date = date("Y-m-d", $startdate);
    /* Set date to today + + days */
    $endate = strtotime("+6 Days");
    /* Check if current date is less than $endate */
        while ($startdate < $endate) { 
        /* If it is less, do a foreach loop for $arrayOfCinemaIds */
            foreach($arrayOfCinemaIds as $id){
            /* Get data from cinelist api */
                $data= file_get_contents('https://api.cinelist.co.uk/get/times/cinema/'.$id.'/?day='.$date);
                $data = json_decode($data);
                /* Find entities that match api_key */
                $find_id = Entity::where('api_key', $id)->get();
                    foreach($find_id as $id_found) {
                        $entity_id = $id_found->id;
                            foreach($data->listings as $listing) {
                                /* Put each record into an array */
                                $title = $listing->title;
                                $time = implode(', ', $listing->times);
                            $films[] = [
                                'title' => $title,
                                'times' => $time,
                                'entity_id' => $entity_id,
                                'date' => $date,
                                ];
                            }
                        }
                    } 
            /* Increase $startdate by 1 day, display message, and change $date to new date */
            $startdate = strtotime("+1 Days", $startdate);
            $this->info('Scraping for ' .$date. ' done, moving to next one');
            $date = date("Y-m-d", $startdate);
        }
        /* Insert array of films to DB, display message */
        $film = Film::insert($films);
        $this->info('Succesfully Added Films to DB!');
    }

我有这个其他的工匠命令,它工作得很好,那为什么上面的那个没有呢?

【问题讨论】:

  • 声明数组 $newsArray=array();
  • 在函数外声明你的$newsArray=array();,在函数内使用

标签: laravel laravel-5 guzzle


【解决方案1】:

声明数组并使用引用

$newsArray = []
$crawler->filter('div[id=content]>.teaser-50')->each(function ($node, $key) use(&newsArray) {
    //Your loop code.
});

【讨论】:

    【解决方案2】:

    我想你可以试试这个:

    $newsArray = array();
        $crawler->filter('div[id=content]>.teaser-50')->each(function ($node, $key) {
            $title = $node->filter('.plain')->text();
            $datepublished = $node->filter('.dateonline')->text();
            $description = $node->filter('.teaser-link')->text();
            $link = $node->filter('a')->link();
            $link_r = $link->getUri();
            $title = $node->filter('.plain')->text();
            $datepublished = $node->filter('.dateonline')->text();
            $description = $node->filter('.teaser-link')->text();
            $link = $node->filter('a')->link();
            $link_r = $link->getUri();
            $image = $node->filter('img')->image();
            $image_s = $image->getUri();
            $image_s = preg_replace("/thumb_/", "", $image_s);
            $filename = basename($image_s);
            $image_path = ('news-gallery/' . $filename);
            Image::make($image_s)->save(public_path('news-gallery/' . $filename));
            //$id = 1+ $key + 1;
            $newsArray = [
                'title' => $title,
                'datepublished' => $datepublished,
                'description' => $description,
                'link' => $link_r,
                'image' => $image_path,
                ];       
            $this->info('Scraping done for ' .$title. ' succesfully');
        });
        //print_r($newsArray);
        $news = News::insert($newsArray);
    

    希望这对你有用!!!

    【讨论】:

      【解决方案3】:

      您已经在每个函数内部定义了$newsArray 数组并尝试在函数外部进行访问。所以,遇到了这个错误。

      所以,在each()函数之前声明数组

       $newsArray = array();
      

      然后你就可以使用了。

      更新

      你可以在定义数组后在each()函数中使用array_push()

      $element = [ 
              'title' => $title,
              'datepublished' => $datepublished,
              'description' => $description,
              'link' => $link_r,
              'image' => $image_path,
              ];
      
      array_push($newsArray,$element);
      

      然后就可以使用$newsArray插入数据了。

      希望你能理解。

      【讨论】:

      • 现在是print_r,但是数组好像是空的
      • @PrzemekWojtas 使用该数组的引用,如函数 ($node, $key) use(&newsArray)
      • @PrzemekWojtas 您需要在each() 函数之前添加以上行,其他代码无需更改。
      • @PrzemekWojtas 您可以在您编写数组代码的each() 函数中使用array_push() 函数。
      • 我得到:[ErrorException] array_push() 期望参数 1 是数组,给定 null
      猜你喜欢
      • 2022-07-06
      • 2021-08-13
      • 1970-01-01
      • 2023-03-26
      • 1970-01-01
      • 2021-09-20
      • 1970-01-01
      • 1970-01-01
      • 2022-11-10
      相关资源
      最近更新 更多