Strange issue with getting a value from this Associative array

Hi guys.

I have an associative array called $VisitorCountryID

$VisitorCountryID = filter_countries(array('Country' => $_SESSION['UserCountryName'])); 

and the function filter_countries() returns all the information relating to the visitors country from the database.

To find out what we have in the array, we do:

print_r($VisitorCountryID);

and it gives us


Array ( [14] => Array ( [CountryId] => 14 [Country] => Australia [FIPS104] => AS [ISO2] => AU [ISO3] => AUS [ISON] => 36 [Internet] => AU [Capital] => Canberra [Comment] => ISO includes Ashmore and Cartier Islands,Coral Sea Islands [sortOrder] => 1 ) ) 

Which is ok. NOW i just want the CountryId which you can see in the array is 14 therefore I write:

 print_r($VisitorCountryID['CountryId']);

Which should give me 14 but it return blank no output.

I am surprised. What do you think is missing here.

Any response / feedback always welcomed!

Cheers!

If the KEY is 14, you have to index by that key!

print_r($VisitorCountryID[14][‘CountryId’])

works because you need the INDEX. This is why your best bet to get at that would be through a foreach. Index zero is empty, so of course that fails!


foreach ($visitorCountryID as $visitorCountry) {
	echo $visitorCountry['CountryId'],' == ',$visitorCountry['Country'],'<br />';
}

Avoiding the ‘key’ headaches in the first place… though that would echo out each one. Unless you know it’s ‘key’ value or index, you can’t access it’s properties without iterating through the whole array.

This is why when building an array I tend to make the key something useful where possible – though if you are pulling that from a query that’s not exactly possible/practical. (since the key is just whatever index it is completely unrelated to any fields it contains)

The bigger question I guess would be what EXACTLY are you trying to do with the values from it?

Ok thanks for the reply but that echo is not returning what we need.

Now as you can see when we did the print_r() the result we get is:

Array ( [14] => Array ( [CountryId] => 14 [Country] => Australia [FIPS104] => AS [ISO2] => AU [ISO3] => AUS [ISON] => 36 [Internet] => AU [Capital] => Canberra [MapReference] => Oceania [NationalitySingular] => Australian [NationalityPlural] => Australians [Currency] => Australian dollar [CurrencyCode] => AUD [Population] => 19357594 [Title] => Australia [measurement] => metric [Comment] => ISO includes Ashmore and Cartier Islands,Coral Sea Islands [sortOrder] => 1 ) ) 

Did you notice here that we have 14 in the beginning whereas it should begin with [0].

And we are using this function by the way to get this:

$VisitorCountryID = filter_countries(array('Country' => $_SESSION['UserCountryName'])); 

I believe there is something with the function. (normally this function would accept accept as countryID but in our case we have the country Name and to our surprise, it does return the country info array but perhaps not in the proper forms.

Therefore here is the function definition, it is little intimidating :wink: and here it is:

function filter_countries($args=array())
{
	global $connection;
	global $GLOBAL_DATABASE;
	$selectFields = (is_null($args['selectFields'])) ? ' * ' : ((is_array($args['selectFields'])) ? implode(',', $args['selectFields']) : "$args[selectFields]");
	$limit = (isset($args['limit'])) ? " LIMIT $args[limit] " : ' ';
	$order = (isset($args['orderby'])) ? " ORDER BY $args[orderby] " : ' ';
	$unique = array('CountryId');

	$fields = array( 'FIPS104', 'ISO2', 'ISO3', 'ISON', 'Internet', 'Capital', 'MapReference', 'NationalitySingular', 'NationalityPlural', 'Currency', 'CurrencyCode', 'Title', 'Comment');
	foreach ($fields as $f)
	if (isset($args[$f]))
	$sql .= " AND `$f` LIKE '%$args[$f]%' ";
		
	$exactfields = array('Country', 'CountryId');
	foreach ($exactfields as $f)
	{
		if (isset($args[$f . ' ne']))
		$sql .= " AND `$f` != '" . $args[$f . ' ne'] . "' ";
		if (isset($args[$f . ' lt']))
		$sql .= " AND `$f` &lt; '" . $args[$f . ' lt'] . "' ";
		if (isset($args[$f . ' lte']))
		$sql .= " AND `$f` &lt;= '" . $args[$f . ' lte'] . "' ";
		if (isset($args[$f . ' gt']))
		$sql .= " AND `$f` &gt; '" . $args[$f . ' gt'] . "' ";
		if (isset($args[$f . ' gte']))
		$sql .= " AND `$f` &gt;= '" . $args[$f . ' gte'] . "' ";
		if (isset($args[$f]))
		$sql .= " AND `$f` = '" . $args[$f] . "' ";
	}
		
	$numberfields = array( 'Population', 'sortOrder');
	foreach ($numberfields as $f)
	{
		if (isset($args[$f . ' ne']))
		$sql .= " AND `$f` != '" . $args[$f . ' ne'] . "' ";
		if (isset($args[$f . ' lt']))
		$sql .= " AND `$f` &lt; '" . $args[$f . ' lt'] . "' ";
		if (isset($args[$f . ' lte']))
		$sql .= " AND `$f` &lt;= '" . $args[$f . ' lte'] . "' ";
		if (isset($args[$f . ' gt']))
		$sql .= " AND `$f` &gt; '" . $args[$f . ' gt'] . "' ";
		if (isset($args[$f . ' gte']))
		$sql .= " AND `$f` &gt;= '" . $args[$f . ' gte'] . "' ";
		if (isset($args[$f]))
		$sql .= " AND `$f` = '" . $args[$f] . "' ";
	}
	$datefields = array();
	foreach ($datefields as $f)
	{
		if (isset($args[$f . ' ne']))
		$sql .= " AND `$f` != '" . $args[$f . ' ne'] . "' ";
		if (isset($args[$f . ' lt']))
		$sql .= " AND `$f` &lt; '" . $args[$f . ' lt'] . "' ";
		if (isset($args[$f . ' lte']))
		$sql .= " AND `$f` &lt;= '" . $args[$f . ' lte'] . "' ";
		if (isset($args[$f . ' gt']))
		$sql .= " AND `$f` &gt; '" . $args[$f . ' gt'] . "' ";
		if (isset($args[$f . ' gte']))
		$sql .= " AND `$f` &gt;= '" . $args[$f . ' gte'] . "' ";
		if (isset($args[$f]))
		$sql .= " AND `$f` LIKE '%" . $args[$f] . "%' ";
	}

	$select = "select $selectFields from `$GLOBAL_DATABASE`.`Countries` WHERE 1 $sql $order $limit";

	if ($args['verbose'] == true)
	echo $select;
	if (!$result = mysql_query($select, $connection))
	return false;
	$return = array();
	while ($row = mysql_fetch_assoc($result))
	{
		if (file_exists(BASE_DIR . "images/flags/" . strtolower($row['ISO2']) . ".gif"))
		{
			$row['imageLink'] = "/images/flags/" . strtolower($row['ISO2']) . ".gif";
		}
		$return[$row['CountryId']] = $row;
	}
	if ($args['limit'] == 1 || check_if_exists($args, $unique))
	return current($return);
	return $return;
}

What change we need to make in the function definition to get the right info back when the country name is passed to it :slight_smile:

Thanks for the reply, this does prints the number 14 but the problem is that we cannot hard code this values [14] inside the print_r()

This nested array values is generated dynamically for different countries. How can to tackle that in printing the number?

I tried something to get the first value dynamically:

print_r($VisitorCountryID[0]['CountryId'])

Still blank output. What do you suggest.

The countryId is in a nested array identified by key 14, so your code should be

print_r($VisitorCountryID[14]['CountryId']);

Thanks bro I will check this in my code. :slight_smile:

Ok, I think I’m completely misunderstanding what it is you are even trying to do – or you’re using like twenty or thirty times code as is neccessary to do it.

If you are only pulling the information for one country with filter_countries, that monstrous train wreck of a function used to put together a simple query is nothing more than driving with the parking brake on. It’s a perfect example of what’s “wrong” with many ‘library’ solutions to problems.

I’d skip calling that bloated function alltogether and just do:


function getCountryInfo($country) {
	global $connection; 
  global $GLOBAL_DATABASE;
  $query="
		SELECT *
		FROM ".$GLOBAL_DATABASE."Countries
		WHERE Country = '".$country."
		LIMIT 1
	";
	/* jhvh bless short circuit eval ;) */
	if (
		($result=mysql_query($select, $connection)) &&
		($row=mysql_fetch_assoc($result))
	) {
			return $row;
		} 
	}
	return false;
}

That way you either get FALSE out of it, or a single array instead of a parent indexed array, skipping 90% of that excess/unrun code and endless pointless if statements. If nothing else it will execute a hundred times faster.


if ($visitorCountryInfo=getCountryInfo($_SESSION['UserCountryName'])) {
	/* do whatever it is you are doing with $visitorCountryInfo here */
	echo '<pre>',print_r($visitorCountryInfo),'</pre>';
} else {
	echo '
		<p>
			<STRONG>ERROR</strong> - Country not found in database or database error occurred
		</p>';
	/* no country record was retrieved */
}

No more pesky outer array to need the index.

It’s why I hate those types of big fat ‘automated query’ functions – and why if I do want to pre-build queries I do so using prepare/execute using PDO instead of the mySQL_ functions. It’s that type of convoluted fist in the face code that makes for maintenance and maintainability nightmares.