在循环结束时添加到数组

时间:2014-01-13 07:50:04

标签: php arrays parsing loops

在这段代码的最后我想要的是一个数组,它继续在一个数组中添加带有所有$ id的给定数组。

目前代码在数组中执行15,然后被接下来的15个项覆盖。我希望能够在代码末尾的数组中包含数组中的30个项目。

我的代码如下:

$idArray = array();

do {
$html = file_get_html($url);
parseItems($html, $dbh);
sleep_flush($chunks=1); // ADJUST LATER
}

while (!empty($html->find('span[class=load-more-message]', 0)));

$html->clear();
unset($html); 

// -------------------------------------------------

function parseItems($html, $dbh) {

foreach($html->find('div.product-stamp-inner') as $content) {

$detail['itemid'] = filter_var($content->find('a.product-title-link', 0)->href, FILTER_SANITIZE_NUMBER_FLOAT);
$id = $detail['itemid'];
$idArray[] = $id; //Counting and adding items to an array

$detail['title'] = $content->find('span.title', 0)->plaintext;
$description = $detail['title'];

if (!tableExists($dbh, $id, $detail)) {
    echo $id . " > " . $description .  "> Table does not exist >";
    createTable($dbh, $id, $description);
    insertData($dbh, $id, $detail);
    echo "<br>";
} else {
    echo $id . " > " . $description . "> Table already exists >";
    checkData($dbh, $id, $detail);
    echo "<br>";
        }
    }
    print_r($idArray);
}

1 个答案:

答案 0 :(得分:1)

这是因为你在这里重新定义了你的$ idArray:

$idArray = array();

您可以创建类的$ idArray全局/成员变量..或者您可以通过引用传递参数:

$idArray = array();

do {
$html = file_get_html($url);
parseItems($html, $dbh, $idArray);
sleep_flush($chunks=1); // ADJUST LATER
}

while (!empty($html->find('span[class=load-more-message]', 0)));

$html->clear();
unset($html); 

// -------------------------------------------------

function parseItems($html, $dbh, &$idArray) {

foreach($html->find('div.product-stamp-inner') as $content) {

$detail['itemid'] = filter_var($content->find('a.product-title-link', 0)->href, FILTER_SANITIZE_NUMBER_FLOAT);
$id = $detail['itemid'];
$idArray[] = $id; //Counting and adding items to an array

$detail['title'] = $content->find('span.title', 0)->plaintext;
$description = $detail['title'];

if (!tableExists($dbh, $id, $detail)) {
    echo $id . " > " . $description .  "> Table does not exist >";
    createTable($dbh, $id, $description);
    insertData($dbh, $id, $detail);
    echo "<br>";
} else {
    echo $id . " > " . $description . "> Table already exists >";
    checkData($dbh, $id, $detail);
    echo "<br>";
        }
    }
    print_r($idArray);
}