Donal.Lynch.Msc
Donal.Lynch.Msc

Reputation: 3605

Get results from mysql query into an integer array?

I am using a php embedded mysql query as follows:

$query_sample = mysql_query(" 
SELECT left FROM sampleTable WHERE right  = 1 
UNION 
SELECT right FROM sampleTable WHERE left  = 1 
");

where both the "right" and "left" columns are integers.

After this query is executed I want the result set to be assigned into an integer array in php. Is there an effecient approach to converting the results of a query into an integer array??

QUESTION:

I basically want to be able to ask the question: "Is $x in $results_array" after the results set from the query has been assigned to $results_array and $x is any integer.

Any help appreciated guys....

Upvotes: 0

Views: 1758

Answers (2)

Frank
Frank

Reputation: 661

You run through the result and build the array.

If you really need the result to be integers, just pass it through intval. A quick snippet follows.

$query_sample = mysql_query(" 
SELECT left FROM sampleTable WHERE right  = 1 
UNION 
SELECT right FROM sampleTable WHERE left  = 1 
");
$result = array();
while($r = mysql_fetch_array($query_sample, MYSQL_NUM)){
    $result[] = intval($r[0]);
}

var_dump($result);

Edit: Sorry. I messed up with things. Just corrected it.


I basically want to be able to ask the question: "Is $x in $results_array"

Do it using MySQL! It is optimized for doing such things fast. Especially if you have set the indexes right.

Upvotes: 1

CrayonViolent
CrayonViolent

Reputation: 32532

php is a loosely typed language, so generally, it doesn't really matter whether it's "10" or 10. php will properly evaluate it as an integer if you were to do like

$x = "10";
$y = $x * 10; // assigns 100

..but if you really want to find out if it can be an integer, you can use is_int()

Or if you want to specifically type cast it, you can do like

$x = intval($x);

or

$x = (int) $x;

edit: (response to comment below)

re: "getting the results into an array"

When you perform a query, you get a result source returned. In order to put the returned data into an array, you need to loop through the result source and assign to an array. Example:

$result = mysql_query($querystring);
while ($row = mysql_fetch_assoc($result)) {
  $array[] = $row['columnname'];
}

Upvotes: 0

Related Questions