php, foreach in foreach
In this code, there are two foreachs. It worked fine when I use it separately. However, it doesn't work together. I've been struggling with this problem for two days..
$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);
}
}
}
}
}
When I send multiple values, this code only save one data. It supposes to save multiple data. Can you see the problem?
Answer
Solution:
The only obvious issue is that in the inner foreach loop, you are setting
which is the same variable you have in the outer foreach loop
Changing one of the variable names should fix the issue.