【问题标题】:Updating an array within an an anonymous function not working在匿名函数中更新数组不起作用
【发布时间】:2016-07-16 18:31:44
【问题描述】:

我正在尝试使用一个名为 Goutte (php scraper/web-crawler) 的包,如下所示:

<?php

// Init
require_once 'vendor/autoload.php';
use Goutte\Client;
$client = new Client();
$reviews = array();

// Parse Review Site
$crawler = $client->request('GET', 'http://review-site-url-here');
$crawler->filter('div.review')->each(function($node) use ($reviews)
{
    // Parse Data
    $player_name = $node->filter('tr.switch > td > a')->first()->text();
    // other fields

    // Build Reviews
    array_push($reviews, [
        'player_name' => $player_name,
        // other fields
    ]);
});

// Debug
echo "<pre>";
print_r($reviews);

当此脚本运行时,$reviews 数组始终为空。但是,如果我在匿名函数中print_r,它似乎只显示每个循环中的当前元素。例如,如果有 4 条评论,我会这样做:

// Parse Review Site
$crawler = $client->request('GET', 'http://review-site-url-here');
$crawler->filter('div.review-BL-mid')->each(function($node) use ($reviews)
{
    // Parse Data
    $player_name = $node->filter('tr.switch > td > a')->first()->text();
    // other fields

    // Build Reviews
    array_push($reviews, [
        'player_name' => $player_name,
        // other fields
    ]);

    // Debug
    print_r($reviews);
});

输出如下:

Array
(
    [0] => Array
        (
            [player_name] => aaaa
        )

)
Array
(
    [0] => Array
        (
            [player_name] => bbb
        )

)
Array
(
    [0] => Array
        (
            [player_name] => ccc
        )

)
Array
(
    [0] => Array
        (
            [player_name] => ddd
        )

)

好像数组永远不会在匿名函数中更新。知道如何解决这个问题吗?

【问题讨论】:

    标签: php arrays goutte domcrawler


    【解决方案1】:

    好的...我在发布此内容并尝试了一些事情后不久就意识到了这个问题。看来我需要通过 reference 传递数组变量$reviews 才能工作;即

    $crawler->filter('div.review')->each(function($node) use (&$reviews) {
       // ...
    });
    

    希望这对其他人有所帮助。

    【讨论】:

      猜你喜欢
      • 2014-08-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-07
      • 2016-01-20
      相关资源
      最近更新 更多