...

View Full Version : loop array values help



ptmuldoon
03-08-2007, 10:02 PM
I'm trying to learn how to loop the values from an array into an sql query. I'm quessing you do this with the foreach function, but I'm pretty lost at the moment on how to accomplish it.

I have the below code, which will look at each row in a table, and echo that field's info into array, giving me values of 10, 12, 31, etc. for each row.

I want to compare those values with another table, but not sure how to proceed.



// Gets all the player capitals
$sql = 'SELECT capitals FROM game_141 WHERE id >= 2';
$playerdata = mysql_query($sql);
while ($row = mysql_fetch_assoc($playerdata)) {
$capitals = $row["capitals"];
$capitals = explode(",",$capitals);
print_r($capitals);
echo '<br />';
}

//Compare each array value to the country id
$sql = "SELECT id, name FROM countries WHERE XXXXXX"//Not sure how to proceed
$q = mysql_query($sql);
while ($a_state = mysql_fetch_assoc($q)){

$STATES[$a_state['id']] = array('name' => $a_state['name']); //
}
print_r($STATES);

_Aerospace_Eng_
03-08-2007, 10:56 PM
You should declare global arrays. Declare $capitals and $STATES out of the while loops. Run the while loops then after that you can use a for loop or foreach. If you know how many states and cities you are going to have then I suggest using a for loop. What exactly would you want to compare? The logic in the for loop will depend on this.
Something like

for($i = 0; $i < 49; $i++)
{
if($capitals[$i] == $STATES[$i])
{
// do something
}
}
Since each state can have only one capital their rows should correspond to each other.

timgolding
03-08-2007, 11:54 PM
ptmuldoon,

From what I can see from the code posted the sql is being selected and inserted in to an array where as in your comment you suggested it was the other way around where the array was being inserted to the sql. I guess by your code and further comments that you do want to insert from the sql to an array and compare it with another array?

If this is the case then here is an expansion on the code posted by yourself and _Aerospace_ :



<?PHP

// Gets all the player capitals
$sql = 'SELECT capitals FROM game_141 WHERE id >= 2';
$playerdata = mysql_query($sql);

// One way is to use an incrmental integer such as i
$i=-1
while ($row = mysql_fetch_assoc($playerdata)) {
//now inside the while loop I can increment i by 1
$i++;
$capitals[$i] = $row["capitals"]; //I am now writing each value from the field capitals into an array
// $capitals = explode(",",$capitals); Please explain this explode function!
}
print_r($capitals);
echo '<br />';
}

// Compare each array value to the country id
// This array is indexed using with a string
$sql = "SELECT id, name FROM countries WHERE XXXXXX"//Not sure how to proceed
$q = mysql_query($sql);
while ($a_state = mysql_fetch_assoc($q)){

$STATES[$a_state['id']] = array('name' => $a_state['name']); //
}
print_r($STATES);


// We can loop the array that is indexed by string as follows
foreach($a_state as $this_element)
{
for($i = 0; $i < sizeof($capitals); $i++)
{
if($capitals[$i] == $this_element)
{
echo "MATCH FOUND!";
}
}
}
?>

_Aerospace_Eng_
03-08-2007, 11:57 PM
Would both the $capitals and $STATES arrays need to be declared outside of the while loops or are they global the moment they are created? I guess I am thinking this way because in javascript if you declare a variable in a function its only available to that function and nothing else.

Inigoesdr
03-08-2007, 11:59 PM
Would both the $capitals and $STATES arrays need to be declared outside of the while loops or are they global the moment they are created? I guess I am thinking this way because in javascript if you declare a variable in a function its only available to that function and nothing else.
They would be global unless the loop was inside of a class or function.

_Aerospace_Eng_
03-09-2007, 12:08 AM
Ahh thanks for clearing that up.

ptmuldoon
03-09-2007, 12:40 AM
Thanks for the help thus far guys. I'm still a bit confused, and googling around on Global Arrays as well.

Regarding the question of why I am exploding the $capitals. This is because each row may have mulitiple values. So if I have 5 rows of data, they would look something like this sample data

"12,19,31,6"
"17,4"
"10"
"8,4,1"
"9,2"

And I want to compare each number from each row to the other table. Thus, I would think to first explode the values from each row. From there to try and compare them.

Thus, unfortunately, the following code:
$i=-1;
while ($row = mysql_fetch_assoc($playerdata)) {
//now inside the while loop I can increment i by 1
$i++;
$capitals[$i] = $row["capitals"]; //I am now writing each value from the field capitals into an array
//$capitals = explode(",",$capitals); //Please explain this explode function!
}
print_r($capitals);

Will give
Array ( [0] => 8,16,17,31 [1] => 1 [2] => 19 [3] => 11 [4] => 43 [5] => 24 )

Thus, I can't compare the value of "8,16,17,31".

I'm gonna keep at it, but could always use some more advice on how to proceed.

timgolding
03-09-2007, 12:46 AM
Ok so the bottom part of my code posted originally is the part that is comparing it looks at the first element in a_state then compare that to every single value in capitals then looks at the second element in a_state and compare that to every single value in capitals and so forth.

If you are attempting to do something different let me know

ptmuldoon
03-09-2007, 01:42 AM
Ok so the bottom part of my code posted originally is the part that is comparing it looks at the first element in a_state then compare that to every single value in capitals then looks at the second element in a_state and compare that to every single value in capitals and so forth.

If you are attempting to do something different let me know

Correct, except the first part of your code treated each field as one value, When I need to separate out (explode) the values from each field first, and then compare them all.

timgolding
03-09-2007, 01:49 AM
Ok so here you should explode when you compare and nest an extra loop for comparing all the exploded elements. like so


<?PHP

// Gets all the player capitals
$sql = 'SELECT capitals FROM game_141 WHERE id >= 2';
$playerdata = mysql_query($sql);

// One way is to use an incrmental integer such as i
$i=-1
while ($row = mysql_fetch_assoc($playerdata)) {
//now inside the while loop I can increment i by 1
$i++;
$capitals[$i] = $row["capitals"]; //I am now writing each value from the field capitals into an array
// $capitals = explode(",",$capitals); Please explain this explode function!
}
print_r($capitals);
echo '<br />';
}

// Compare each array value to the country id
// This array is indexed using with a string
$sql = "SELECT id, name FROM countries WHERE XXXXXX"//Not sure how to proceed
$q = mysql_query($sql);
while ($a_state = mysql_fetch_assoc($q)){

$STATES[$a_state['id']] = array('name' => $a_state['name']); //
}
print_r($STATES);


// We can loop the array that is indexed by string as follows
foreach($a_state as $this_element)
{
for($i = 0; $i < sizeof($capitals); $i++)
{
$exploded = explode(",",$capitals[$i]);
foreach($exploded as $value)
{
if($value == $this_element)
{
echo "MATCH FOUND!";
}
}
}
}
?>

timgolding
03-09-2007, 01:52 AM
You are in effect handling a mutli-dimensional array so this is why we need three loops to compare them

ptmuldoon
03-09-2007, 02:37 AM
Thanks for taking the time to help. The one thing I still haven't grasped well is using foreach.

And working with what you've shown me, I'm getting an error or "Invalid argument supplied for foreach()"

I quess this likely has to do with $this_element variable. I've made good strides in learning php, but really wish I understand that function better.


// Gets all the player capitals
$sql = 'SELECT capitals FROM game_141 WHERE id >= 2';
$playerdata = mysql_query($sql);

// One way is to use an incremental integer such as i
$i=-1;
while ($row = mysql_fetch_assoc($playerdata)) {
//now inside the while loop I can increment i by 1
$i++;
$capitals[$i] = $row["capitals"];
}
print_r($capitals);
echo '<br />';

// Compare each array value to the country id
// This array is indexed using with a string
$sql = "SELECT id, name FROM countries WHERE id < 44 ORDER BY name ASC"; // 44 being the first wildcard
$q = mysql_query($sql);
while ($a_state = mysql_fetch_assoc($q)){

$STATES[$a_state['id']] = array('name' => $a_state['name']); //
}
print_r($STATES);


// We can loop the array that is indexed by string as follows
foreach($a_state as $this_element){
for($i = 0; $i < sizeof($capitals); $i++)
{
$exploded = explode(",",$capitals[$i]);
foreach($exploded as $value)
{
if($value == $this_element)
{
echo "MATCH FOUND!";
}
}
}
}

timgolding
03-09-2007, 12:00 PM
Sorry mate I was vely tired last night its because I was trying to run the foreach on a sql assciation i guess. but I intended to do this on the arra STATES



// Gets all the player capitals
$sql = 'SELECT capitals FROM game_141 WHERE id >= 2';
$playerdata = mysql_query($sql);

// One way is to use an incremental integer such as i
$i=-1;
while ($row = mysql_fetch_assoc($playerdata)) {
//now inside the while loop I can increment i by 1
$i++;
$capitals[$i] = $row["capitals"];
}
print_r($capitals);
echo '<br />';

// Compare each array value to the country id
// This array is indexed using with a string
$sql = "SELECT id, name FROM countries WHERE id < 44 ORDER BY name ASC"; // 44 being the first wildcard
$q = mysql_query($sql);
while ($a_state = mysql_fetch_assoc($q)){

$STATES[$a_state['id']] = array('name' => $a_state['name']); //
}
print_r($STATES);


// We can loop the array that is indexed by string as follows
foreach($STATES as $this_element){
for($i = 0; $i < sizeof($capitals); $i++)
{
$exploded = explode(",",$capitals[$i]);
foreach($exploded as $value)
{
if($value == $this_element)
{
echo "MATCH FOUND!";
}
}
}
}



foreach (http://uk.php.net/manual/en/control-structures.foreach.php) is a very useful functon for lopping array. It has little interest in the index as it just incrments the internal array pointer by 1 each time.

P.s When posted PHP rather than using [code] it would be cool for you to use [php]

aedrin
03-09-2007, 05:25 PM
This:



$array = array("element", "element2", "element3");

foreach ($array as $element) {
echo $element;
}


Is basically this:



$array = array("element", "element2", "element3");

for ($i = 0;$i < sizeof($array);$i++) {
$element = $array[$i];
echo $element;
}


As you can see, the first one is much cleaner to read. But remember that foreach can be slower than using a for() loop.

You can either do:



foreach ($array as $element) {
}


Where $element is the actual element of the array. Or this



foreach ($array as $key => $element) {
}


Where $key becomes the index of that element. This is quite helpful. As the alternative to that would be:



$array = array("element", "element2", "element3");
$keys = array_keys($array);
for ($i = 0;i < sizeof($keys);$i++) {
$key = $keys[$i]
$element = $array[$key];
echo $key . '=' . $element;
}


Which is even harder to read.

I've never heard of the term 'global arrays'. When you define a variable in PHP outside of a function or a class, it is automatically global. So I'm assuming that is what he meant, declare an array.

ptmuldoon
03-10-2007, 05:34 PM
Aerospace and TimGolding:

Thanks for your both of your's help. After digesting as much as that as I could, I was able to figure out and set up the below code, which both works for me, and something I can understand.

I did get a foreach error for a row with no capital/element in it, but was able to work around that by simple placing a default value in the field during the table creation.


$sql = "SELECT players FROM games WHERE id = 141";
$num_players = get_one($sql);
$num_players = $num_players +1;

for ($i=2; $i<=$num_players; $i++){
$sql = "SELECT capitals FROM game_141 WHERE id = $i";
$data = mysql_query($sql);
$row = mysql_fetch_assoc($data);
$capitals = explode(",", $row["capitals"]);

foreach ($capitals as $element) {
$sql = "SELECT name FROM countries WHERE id = $element ";
$data = mysql_query($sql);
$row = mysql_fetch_assoc($data);
$name = $row['name'];
echo $name;
echo '<br />';
}
}



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum