...

View Full Version : create array from while loop



prostcode
07-10-2007, 10:24 AM
$query = "SELECT * FROM table";
$result = mysql_query($query);

while($rows = mysql_fetch_array($result)){
$code=$rows['code'];
$pt=$rows['points'];
$code_array = array($code);

foreach($code_array as $key => $value) {
echo $key. " " . $value . "<br>";
}

}


instead the output is:


0 Code1
0 Code2
0 Code3
0 Code4
0 Code5


I want the output to be:


0 Code1
1 Code2
2 Code3
3 Code4
4 Code5

StupidRalph
07-10-2007, 11:34 AM
$query = "SELECT * FROM table";
$result = mysql_query($query);
$code_array = array();

while($rows = mysql_fetch_array($result)){
$code=$rows['code'];
$pt=$rows['points'];
$code_array[] = $code;

foreach($code_array as $key => $value) {
echo $key. " " . $value . "<br>";
}

}

Try this instead...I have not tested it...

prostcode
07-11-2007, 03:03 AM
$query = "SELECT * FROM table";
$result = mysql_query($query);
$code_array = array();

while($rows = mysql_fetch_array($result)){
$code=$rows['code'];
$pt=$rows['points'];
$code_array[] = $code;

foreach($code_array as $key => $value) {
echo $key. " " . $value . "<br>";
}

}

Try this instead...I have not tested it...

thanks. it works this time but the output looks weird



0 Code1
0 Code1
1 Code2
2 Code3
3 Code4
0 Code5
0 Code5



How? Actually I want to do sorting. I want to get the duplicate values to do some comparison. Do you know how?

StupidRalph
07-11-2007, 04:46 PM
$query = "SELECT * FROM table";
$result = mysql_query($query);
$code_array = array();

while($rows = mysql_fetch_array($result)){
$code=$rows['code'];
$pt=$rows['points'];
$code_array[] = $code;
}

foreach($code_array as $key => $value) {
echo $key. " " . $value . "<br>";
}



Pull the foreach out of the while loop. PHP has a lot of different sort functions. Consult the php manual (http://www.php.net/array)



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum