将多列添加到数组

卡罗尔·卡尔

我想将我通过网络抓取的几个值添加到最终结果数组中。我抓取的每个值都代表数组中的一列。

请参阅下面我尝试的内容:

<?php
require_once 'vendor/autoload.php';

use Goutte\Client;

$client = new Client();
$cssSelector = 'tr';
$coin = 'td.no-wrap.currency-name > a';
$url = 'td.no-wrap.currency-name > a';
$symbol = 'td.text-left.col-symbol';
$price = 'td:nth-child(5) > a';

$result = array();

$crawler = $client->request('GET', 'https://coinmarketcap.com/all/views/all/');

$crawler->filter($coin)->each(function ($node) {
    print $node->text()."\n";
    array_push($result, $node->text());
});

$crawler->filter($url)->each(function ($node) {
    $link = $node->link();
    $uri = $link->getUri();
    print $uri."\n";
    array_push($result, $uri);
});

$crawler->filter($symbol)->each(function ($node) {
    print $node->text()."\n";
    array_push($result, $node->text());
});

$crawler->filter($price)->each(function ($node) {
    print $node->text()."\n";
    array_push($result, $node->text());
});

print_r($result); 

我的问题是单个结果不会被推送到数组。任何建议为什么?

有没有更好的方法向数组添加多个属性?

我感谢您的回复!

普通吐司

$result 在您的闭包中未知。

尝试 USE 在过滤器闭包中包含外部变量 $result ,如下所示:

$crawler->filter($coin)->each(function ($node) use (&$result) {
    print $node->text()."\n";
    array_push($result, $node->text());
});

http://php.net/manual/en/class.closure.php

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章