Jump to content

How to make a variable live outside a foreach()


lopes_andre

Recommended Posts

Hi,

 

I'm working in a Class, I have a method that have a foreach and I need to make live a variable outside them(foreach).

 

		// Vou passar os HREF's um a um
		foreach($matches as $match) {

			// Aqui vou verificar se o link termina em ".zip"
			if (preg_match("/.zip$/", $match[2])) {

				// Vou verificar qual o $csvType
				if ($this->csvType == 'geolitecity') {

					// Tenho de apanhar todos com a palavra "city" para o array "$match_word"
					$match_word[$i] = $this->obtainWordWithWordInArray('city', $match[2]);
					//print_r($match_word[$i]);

				} elseif ($this->csvType == 'geolitecountry') {

					// Tenho de apanhar todos com a palavra "country" para o array "$match_word"
					$match_word[$i] = $this->obtainWordWithWordInArray('country', $match[2]);

					// Retorna o nome do ficheiro a fazer download (A ACABAR, falta verificar parte do nome!!!!!)
					//$downloadFileName = $match[2]; DESCOMENTAR!!!!!!
				}
			} else {

				// Neste caso não vou fazer nada, deveria mostrar um erro aqui
				// echo "Other - " . $match[2] . "<br />"; // Para efeitos de Debug
			}

		// Adicionar mais 1 ao contador
		$i++;
		}

 

How can I make the variable "$match_word[$i]" live outside this foreach, it is possible to declare a variable as global? How can I do that?

 

Best Regards,

Link to comment
Share on other sites

As long as your foreach loop is not inside of a class and using private or protected variables  you should be free to call the $var[$i] anytime after during or after the loop, and since you have already been smart enough to loop each variable into an array you don't have to worry about values overwriting each other.

 

If you are unsure of what your array looks like, or if the values are being added at all just do:

print_r($match_word);

Link to comment
Share on other sites

Hi,

 

I think I have discovered the problem, but it is not working yet.

 

The full method is this:

 

public function obtainDownloadFileName() {

	// Vou apanhar o conteúdo do html que lista os ficheiros
	$url = $this->url_without_file; // o $this->url_without_file é p.e. 'http://geolite.maxmind.com/download/geoip/database/GeoLiteCity_CSV/'
	$input = @file_get_contents($url) or die("Could not access file: $url");
	$regexp = "<a\s[^>]*href=(\"??)([^\" >]*?)\\1[^>]*>(.*)<\/a>"; 

	// Agora vou listar os HREF's
	if(preg_match_all("/$regexp/siU", $input, $matches, PREG_SET_ORDER)) 
	{ 
		// Vou passar os HREF's um a um
		foreach($matches as $match) {

			// Aqui vou verificar se o link termina em ".zip"
			if (preg_match("/.zip$/", $match[2])) {

				// Vou verificar qual o $csvType
				if ($this->csvType == 'geolitecity') {

					// Tenho de apanhar todos com a palavra "city" para o array "$match_word"
					$match_word[$i] = $this->obtainWordWithWordInArray('city', $match[2]);
					//echo ($match_word[$i]); // P efeitos de DEBUG, apagar.
					//$teste22 = $match_word[$i]; // P efeitos de DEBUG, apagar.

				} elseif ($this->csvType == 'geolitecountry') {

					// Tenho de apanhar todos com a palavra "country" para o array "$match_word"
					$match_word[$i] = $this->obtainWordWithWordInArray('country', $match[2]);

					// Retorna o nome do ficheiro a fazer download (A ACABAR, falta verificar parte do nome!!!!!)
					//$downloadFileName = $match[2]; DESCOMENTAR!!!!!!
				}
			} else {

				// Neste caso não vou fazer nada, deveria mostrar um erro aqui
				// echo "Other - " . $match[2] . "<br />"; // Para efeitos de Debug
			}

		// Adicionar mais 1 ao contador
		$i++;
		}

		// Agora vou ver qual o ficheiro mais recente
		if ($this->csvType == 'geolitecity') {

			// Vou buscar a data mais recente da lista de ficheiros
			//echo ($match_word[$i]);
			//$mostRecentDate = $this->obtainMostRecentFile($match_word[$i], '12', '8');
			//echo $mostRecentDate;
			// Vou agora 

		} elseif ($this->csvType == 'geolitecountry') {

			// Este não faz mt sentido passar aqui(já foi achado lá em cima), mas p ficar como o outro
			$downloadFileName = $match_word[$i];

		} else { 
			// Neste caso não vou fazer nada, DEVERIA mostrar um erro.
		}

		// Aqui listo 
		//print_r($match_word); // Para efeitos de DEBUG, apagar.
	} 
	return $downloadFileName; // "GeoLiteCity_20101201.zip"
}

 

The problem is in here:

 

		// Vou passar os HREF's um a um
		foreach($matches as $match) {

			// Aqui vou verificar se o link termina em ".zip"
			if (preg_match("/.zip$/", $match[2])) {

				// Vou verificar qual o $csvType
				if ($this->csvType == 'geolitecity') {

					// Tenho de apanhar todos com a palavra "city" para o array "$match_word"
					$match_word[$i] = $this->obtainWordWithWordInArray('city', $match[2]);
					//echo ($match_word[$i]); // P efeitos de DEBUG, apagar.
					//$teste22 = $match_word[$i]; // P efeitos de DEBUG, apagar.

				} elseif ($this->csvType == 'geolitecountry') {

					// Tenho de apanhar todos com a palavra "country" para o array "$match_word"
					$match_word[$i] = $this->obtainWordWithWordInArray('country', $match[2]);

					// Retorna o nome do ficheiro a fazer download (A ACABAR, falta verificar parte do nome!!!!!)
					//$downloadFileName = $match[2]; DESCOMENTAR!!!!!!
				}
			} else {

				// Neste caso não vou fazer nada, deveria mostrar um erro aqui
				// echo "Other - " . $match[2] . "<br />"; // Para efeitos de Debug
			}

		// Adicionar mais 1 ao contador
		$i++;
		}

 

In this foreach() the variable "$match_word[$i]" it is not realy an Array, because I can display it like this "echo ($match_word[$i]);".

 

And this variable is giving me an output like:

 

GeoLiteCity_20090601.zipGeoLiteCity_20090701.zipGeoLiteCity_20090801.zipGeoLiteCity_20090901.zipGeoLiteCity_20091001.zipGeoLiteCity_20091101.zipGeoLiteCity_20091201.zipGeoLiteCity_20100101.zipGeoLiteCity_20100201.zipGeoLiteCity_20100301.zipGeoLiteCity_20100401.zipGeoLiteCity_20100501.zipGeoLiteCity_20100601.zipGeoLiteCity_20100701.zipGeoLiteCity_20100801.zipGeoLiteCity_20100901.zipGeoLiteCity_20101001.zipGeoLiteCity_20101101.zipGeoLiteCity_20101201.zip

 

Instead of this:

 

array ( 5 => 'GeoLiteCity_20090601.zip',
			 6 => 'GeoLiteCity_20090701.zip',
			 7 => 'GeoLiteCity_20090801.zip',
			 8 => 'GeoLiteCity_20090901.zip',
			 9 => 'GeoLiteCity_20091001.zip',
			 10 => 'GeoLiteCity_20091101.zip',
			 11 => 'GeoLiteCity_20091201.zip',
			 12 => 'GeoLiteCity_20100101.zip',
			 13 => 'GeoLiteCity_20100201.zip',
			 14 => 'GeoLiteCity_20100301.zip',
			 15 => 'GeoLiteCity_20100401.zip',
			 16 => 'GeoLiteCity_20100501.zip',
			 17 => 'GeoLiteCity_20100601.zip',
			 18 => 'GeoLiteCity_20100701.zip',
			 19 => 'GeoLiteCity_20100801.zip',
			 20 => 'GeoLiteCity_20100901.zip',
			 21 => 'GeoLiteCity_20101001.zip',
			 22 => 'GeoLiteCity_20101101.zip',
			 23 => 'GeoLiteCity_20101201.zip'
		   );

 

My question: In this foreach how can I generate an array like this one?

 

Best Regards,

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.