HiveBrain v1.2.0
Get Started
← Back to all entries
patternphpMinor

Merging website info into an array

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
websiteinfomergingarrayinto

Problem

I'm scraping a title and a link from a website and placing them in a single array.
The $i variable seems a bit wrong to me, or is it perfectly fine?

$linkQuery = $xpath->query("//div[@class='news-archive']//a/@href");
$titleQuery = $xpath->query("//div[@class='news-archive']//a");

$data = [];

foreach ($linkQuery as $link) {
    $data[] = array('link' => $link->value);
}

$i = 0;
foreach ($titleQuery as $title) {
    $data[$i]['title'] = $title->nodeValue;
    $i++;
}


I do like the structure of the Array:

Array (
    [0] => Array
        (
            [link] => http://www.gpupdate.net/nl/f1-nieuws/321783/force-india-vreest-voor-deelname-aan-laatste-test/
            [title] => Force India vreest voor deelname aan laatste test
        )

Solution

I think that one of the collections you iterate already has all the data you need. Try this:

$linkQuery = $xpath->query("//div[@class='news-archive']//a");
foreach ($linkQuery as $link) {
    $data[] = array('link' => $link->getAttribute('href'), 'title' => $link->nodeValue);
}


Btw. array_map() is another way for traversing two (or more) arrays simultaneously:

$group_elements = function($link, $title) {
    return array('link' => $link->value, 'title' => $title->nodeValue);
};
$data = array_map($group_elements, $linkQuery, $titleQuery);

Code Snippets

$linkQuery = $xpath->query("//div[@class='news-archive']//a");
foreach ($linkQuery as $link) {
    $data[] = array('link' => $link->getAttribute('href'), 'title' => $link->nodeValue);
}
$group_elements = function($link, $title) {
    return array('link' => $link->value, 'title' => $title->nodeValue);
};
$data = array_map($group_elements, $linkQuery, $titleQuery);

Context

StackExchange Code Review Q#79901, answer score: 5

Revisions (0)

No revisions yet.