【问题标题】:How do I access a variable in PHP inside a foreach loop?如何在 foreach 循环中访问 PHP 中的变量?
【发布时间】:2021-06-01 18:19:52
【问题描述】:

我正在 webscraping 使用 php 中的 Goute Library 来自 this link 的表格。

下面是我的代码

    $client = new Client();
    $crawler = $client->request('GET', 'https://www.worldometers.info/world-population/population-by-country/');
    $crawler->filter('#example2 tbody')->filter('tr')->each(function ($node) {

       $country = new Country(); // I have declared country here.
       $test = "TOday";   //I have a variable Test

        $node->filter('td')->each(function ($td,$i){

            switch ($i){
                case 1:
                    $country_name = $td->text();

                    echo $test; //I cannot access test here.
                    $country->name = $country_name; //I am not able to access the declared Country here

                    break;
                case 2:
                    //todo case 2
                    break;
                case 3:
                    //todo case 3
                    break;
                case 4:
                    //todo case 4
                    break;
            }
        });

        echo "<br><br><br>";

    });

我的代码包含两个 foreach 循环。在第一个循环中,我声明了我想在第二个循环中访问的变量 $test 和 $country。

但是,每当我尝试访问变量时,我都会收到错误消息:

“未定义变量:测试”

下面是 PhpStorm 的截图。

为什么我无法访问这些已明确声明甚至初始化的变量?

【问题讨论】:

    标签: php laravel goutte


    【解决方案1】:

    如果你想在你的函数 clouser 中访问这个变量,你应该告诉那个函数使用它们:

     $crawler->filter('#example2 tbody')->filter('tr')->each(function ($node)use( $country) {
    
       $country = new Country(); // I have declared country here.
       $test = "TOday";   //I have a variable Test
    

    如果您想使用另一个变量,只需将其添加到函数参数中:

    ->each(function ($node)use( $country,$secondVariable,$thirdVariable ...)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-26
      • 1970-01-01
      • 2021-01-21
      • 1970-01-01
      • 1970-01-01
      • 2012-11-11
      相关资源
      最近更新 更多