简体   繁体   中英

How do I access a variable in PHP inside a foreach loop?

I am webscraping a table from this link using the Goute Library in php.

Below is my code

    $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>";

    });

My code contains two foreach loops. Inside the first loop I am declaring variable $test and $country which I would like to access inside my second loop.

However, whenever I try to access the variables, I am getting the error:

"Undefined variable: test"

Below is a screenshot from PhpStorm. 在此处输入图像描述

Why am I not able to access these variables which have clearly been declared and even initialized?

if you want to access this variables iniside your function clouser, you should tell that function to use them:

 $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

if you have another vaiable you want to use, just add it to function argument:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM