2

I'm very new to this so I could be going in completely the wrong direction.

I'm using a web crawler library I want to return an array of results for each page I scrape. My problem isn't with the scraper though.

I have start with an indexed array $links whose values are the urls I want to scrape for information. if I go:

foreach ($links as $key=>$value) {
    $crawler = $client->request('GET', $value);
    $crawler->filter('p.scores')->each(function ($node) {
        $thisscore = $node->text();
        print $thisscore;
        });
};

it prints out all the results on the screen but I want the results to be in a different array for each of the foreach loops i.e. end up with @results0 @results1 @results2

2
  • 1
    Just take it in an array variable $results[]=$thisscore;.
    – Rikesh
    Feb 16, 2014 at 12:17
  • What does that do? I need to have separate arrays for each entry in the $links array. I'm still confused.
    – Felix G
    Feb 16, 2014 at 12:26

1 Answer 1

2

Just create an array and populate it at each iteration

$new_array = array();
foreach ($links as $key=>$value) {
    $crawler = $client->request('GET', $value);
    $crawler->filter('p.scores')->each(function ($node) {
        $thisscore = $node->text();
       // print $thisscore;
        $new_array[] = $thisscore;
    });
};

Now you have all results in your $new_array

6
  • Variables are not global by default in PHP. For closures, you should use the use keyword.
    – Mark
    Feb 16, 2014 at 12:19
  • Thank you but doesn't that put all my results into one array whereas I want separate arrays for each of the $links
    – Felix G
    Feb 16, 2014 at 12:27
  • Try to put this $new_array[][] = $thisscore; so you will have one sub array each iteration
    – Fabio
    Feb 16, 2014 at 12:29
  • That's empty when I print_r it outside the foreach. I don't know what I'm doing wrong.
    – Felix G
    Feb 16, 2014 at 12:36
  • You are populating the array in the loop so you are abke to print_r($new_array); outside the loop
    – Fabio
    Feb 16, 2014 at 13:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.