Page 1 of 1

Query result into an array dynamically.

Posted: Fri Jan 08, 2010 6:15 am
by sakayaya
I am a newbie with php and will appreciate any help I can get. Thanks in advance.

I want to dynamically insert a query result into an array and use the elements in the array to check with a variable if the value of the variable exists in the array. I have managed to do the latter with an array I created. However I want this done dynamically as differrent query results will mean different array values. Please find a snippet of the code I generated;

<?php

//some php code here

$query="SELECT * FROM pictures_thumbs WHERE id='$album_id' LIMIT $start,$per_page";
$thumbs= mysql_query($query) or die(mysql_error());
// some php code here
echo '<table>';
echo '<tr>';
while($row=mysql_fetch_array($thumbs)){

$new_array=array(); //Here is the empty array to insert array elements from $row
$new_array=array();
if (!in_array ($row, $new_array)) {
$new_array[]=$row['thumb_id'];// all thumb_id's inserted here.
$new_array=array_unique($new_array);
/* when I do print_r($new_array); I get a result printed out as
Array([0]=>27)
Array([0]=> 28)
Array([0]=> 29)
However this is not right for me because I want the keys of the array to increment like Array([0]=>27,[1]=>28,[2]=>29,[3]=>30 )and not [0],[0],[0] as the print_r result shows above.
*/

I will appreciate any help or suggestions. Thanks in advance.






?>

Re: Query result into an array dynamically.

Posted: Fri Jan 08, 2010 11:28 am
by manohoo
Read this for finding arrays within arrays:
http://php.net/manual/en/function.in-array.php

After reading your code a second time I understand better what you are looking for.

I would force the array index in the while loop:

$i=0;
while (...) {
...
$new_array[$i] = 'whatever';
$i++;

}

Re: Query result into an array dynamically.

Posted: Fri Jan 08, 2010 5:47 pm
by sakayaya
Thanks a bunch manohoo. It worked like magic. God bless u.

$i=0;
while($row=mysql_fetch_array($thumbs)){
$new_array=array();
$new_array[$i]=$row['thumb_id'];
$i++;
print_r($new_array);

//Print result
Array ([0] =>27)
Array ([1] =>28)
Array ([2] =>29)
Array ([3] =>30)
Array ([4] =>31)
Array ([5] =>33)