php,foreach in foreach

时间:2013-01-04 07:44:35

标签: php foreach

在此代码中,有两个foreach。我单独使用它时工作正常。但是,它不能一起工作。我已经在这个问题上苦苦挣扎了两天..

$urls = nl2br($this->input->post('urls'));
$result = explode("<br />", $urls);

$n = 0;
foreach($result as $row)
{
$n++;   
    $Google_Play_URL = $row;
    $string = file_get_contents($Google_Play_URL);

    $dom = new DOMDocument();
    @$dom->loadHTML($string);
    $anchors = $dom->getElementsByTagName('a');

    $i = 0;
    foreach ($anchors as $anchor) 
    {
    $i++;

        if ($anchor->nodeValue === 'Email Developer') {
            $email = str_replace('mailto:', '', $anchor->getAttribute('href'));

            if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
                echo $email;

                $id = $this->session->userdata(SESSION_USERID); 

                $country = 'US';
                $type = 'android';

                $query = 'SELECT idx FROM db_advertisers WHERE email = "'.$email.'"';
                $result = $this->db->query($query);

                if($result->num_rows() < 1)
                {
                    $query = 'INSERT INTO db_advertisers (email, type, url, country, submit_user) VALUES ("'.$email.'", "'.$type.'", "'.$Google_Play_URL.'", "'.$country.'", "'.$id.'")';
                    $this->db->query($query);   
                }
            }
        }
    }

}

当我发送多个值时,此代码仅保存一个数据。它假设保存多个数据。你能看到问题吗?

1 个答案:

答案 0 :(得分:5)

唯一明显的问题是,在内部foreach循环中,您正在设置

$result = $this->db->query($query);

与外部foreach循环中的变量相同

foreach($result as $row)

更改其中一个变量名称可以解决问题。