Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 15 of 15
  1. #1
    Regular Coder
    Join Date
    Feb 2005
    Posts
    663
    Thanks
    5
    Thanked 14 Times in 14 Posts

    loop array values help

    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.

    Code:
    // 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);

  • #2
    Supreme Master coder! _Aerospace_Eng_'s Avatar
    Join Date
    Dec 2004
    Location
    In a place far, far away...
    Posts
    19,291
    Thanks
    2
    Thanked 1,043 Times in 1,019 Posts
    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
    PHP Code:
    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.
    ||||If you are getting paid to do a job, don't ask for help on it!||||

  • #3
    Senior Coder timgolding's Avatar
    Join Date
    Aug 2006
    Location
    Southampton
    Posts
    1,519
    Thanks
    114
    Thanked 110 Times in 109 Posts
    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 Code:
    <?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!";
            }
        }

    ?>
    Last edited by timgolding; 03-08-2007 at 11:03 PM.
    You can not say you know how to do something, until you can teach it to someone else.

  • #4
    Supreme Master coder! _Aerospace_Eng_'s Avatar
    Join Date
    Dec 2004
    Location
    In a place far, far away...
    Posts
    19,291
    Thanks
    2
    Thanked 1,043 Times in 1,019 Posts
    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.
    ||||If you are getting paid to do a job, don't ask for help on it!||||

  • #5
    Super Moderator Inigoesdr's Avatar
    Join Date
    Mar 2007
    Location
    Florida, USA
    Posts
    3,647
    Thanks
    2
    Thanked 406 Times in 398 Posts
    Quote Originally Posted by _Aerospace_Eng_ View Post
    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.

  • #6
    Supreme Master coder! _Aerospace_Eng_'s Avatar
    Join Date
    Dec 2004
    Location
    In a place far, far away...
    Posts
    19,291
    Thanks
    2
    Thanked 1,043 Times in 1,019 Posts
    Ahh thanks for clearing that up.
    ||||If you are getting paid to do a job, don't ask for help on it!||||

  • #7
    Regular Coder
    Join Date
    Feb 2005
    Posts
    663
    Thanks
    5
    Thanked 14 Times in 14 Posts
    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:
    PHP 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.

  • #8
    Senior Coder timgolding's Avatar
    Join Date
    Aug 2006
    Location
    Southampton
    Posts
    1,519
    Thanks
    114
    Thanked 110 Times in 109 Posts
    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
    You can not say you know how to do something, until you can teach it to someone else.

  • #9
    Regular Coder
    Join Date
    Feb 2005
    Posts
    663
    Thanks
    5
    Thanked 14 Times in 14 Posts
    Quote Originally Posted by timgolding View Post
    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.

  • #10
    Senior Coder timgolding's Avatar
    Join Date
    Aug 2006
    Location
    Southampton
    Posts
    1,519
    Thanks
    114
    Thanked 110 Times in 109 Posts
    Ok so here you should explode when you compare and nest an extra loop for comparing all the exploded elements. like so
    PHP Code:
    <?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!";
               }
            }
        }

    ?>
    Last edited by timgolding; 03-09-2007 at 12:55 AM.
    You can not say you know how to do something, until you can teach it to someone else.

  • #11
    Senior Coder timgolding's Avatar
    Join Date
    Aug 2006
    Location
    Southampton
    Posts
    1,519
    Thanks
    114
    Thanked 110 Times in 109 Posts
    You are in effect handling a mutli-dimensional array so this is why we need three loops to compare them
    You can not say you know how to do something, until you can teach it to someone else.

  • #12
    Regular Coder
    Join Date
    Feb 2005
    Posts
    663
    Thanks
    5
    Thanked 14 Times in 14 Posts
    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.

    PHP Code:
    // 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!";
                   }
               }
        }


  • #13
    Senior Coder timgolding's Avatar
    Join Date
    Aug 2006
    Location
    Southampton
    Posts
    1,519
    Thanks
    114
    Thanked 110 Times in 109 Posts
    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

    PHP Code:
    // 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 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]
    Last edited by timgolding; 03-10-2007 at 12:44 AM.
    You can not say you know how to do something, until you can teach it to someone else.

  • #14
    Senior Coder
    Join Date
    Jan 2007
    Posts
    1,648
    Thanks
    1
    Thanked 58 Times in 54 Posts
    This:

    PHP Code:
    $array = array("element""element2""element3");

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

    Is basically this:

    PHP Code:
    $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:

    PHP Code:
    foreach ($array as $element) {

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

    PHP Code:
    foreach ($array as $key => $element) {

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

    PHP Code:
    $array = array("element""element2""element3");
    $keys array_keys($array);
    for (
    $i 0;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.

  • #15
    Regular Coder
    Join Date
    Feb 2005
    Posts
    663
    Thanks
    5
    Thanked 14 Times in 14 Posts
    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.

    PHP Code:
    $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 />';         
        }



  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •