www.webdeveloper.com
Results 1 to 3 of 3

Thread: How loops "foreach" works / applies

Hybrid View

  1. #1
    Join Date
    Oct 2006
    Posts
    10

    How loops "foreach" works / applies

    So I know the code listed below has some functions that you won't be familiar with, but that shouldn't change the basics. I'm very new to programming and the concept of passing an array to a function and having it performed foreach "whatever" doesn't seem to make any sense to me.

    Take a look at this example code:

    I'm trying to figure out how I would loop through a list of classes which I can obtain by running GetMetadataInfo(). This code says "or set through a loop" which obviously should be very easy, but I'm racking my brain to figure out how to make this "loop" work. I have the code to put all the "$table_name" variables into an array, but then I cant seem to make a loop to create the "echo SQL" line for each class.
    Code:
    // gets resource information.  need this for the KeyField
    $rets_resource_info = $rets->GetMetadataInfo();
    
    $resource = "Property";
    $class = "RES";
    // or set through a loop
    
    // pull field format information for this class
    $rets_metadata = $rets->GetMetadata($resource, $class);
    
    $table_name = "rets_".strtolower($resource)."_".strtolower($class);
    // i.e. rets_property_res
    
    $sql = create_table_sql_from_metadata($table_name, $rets_metadata, $rets_resource_info[$resource]['KeyField']);
    echo "$sql";
    
    
    function create_table_sql_from_metadata($table_name, $rets_metadata, $key_field, $field_prefix = "") {
    
            $sql_query = "CREATE TABLE {$table_name} (\n";
    
            foreach ($rets_metadata as $field) {
    
                    $field['SystemName'] = "`{$field_prefix}{$field['SystemName']}`";
    
                    $cleaned_comment = addslashes($field['LongName']);
    
                    $sql_make = "{$field['SystemName']} ";
    
                    if ($field['Interpretation'] == "LookupMulti") {
                            $sql_make .= "TEXT";
                    }
                    elseif ($field['Interpretation'] == "Lookup") {
                            $sql_make .= "VARCHAR(50)";
                    }
                    elseif ($field['DataType'] == "Int" || $field['DataType'] == "Small" || $field['DataType'] == "Tiny") {
                            $sql_make .= "INT({$field['MaximumLength']})";
                    }
                    elseif ($field['DataType'] == "Long") {
                            $sql_make .= "BIGINT({$field['MaximumLength']})";
                    }
                    elseif ($field['DataType'] == "DateTime") {
                            $sql_make .= "DATETIME default '0000-00-00 00:00:00' not null";
                    }
                    elseif ($field['DataType'] == "Character" && $field['MaximumLength'] <= 255) {
                            $sql_make .= "VARCHAR({$field['MaximumLength']})";
                    }
                    elseif ($field['DataType'] == "Character" && $field['MaximumLength'] > 255) {
                            $sql_make .= "TEXT";
                    }
                    elseif ($field['DataType'] == "Decimal") {
                            $pre_point = ($field['MaximumLength'] - $field['Precision']);
                            $post_point = !empty($field['Precision']) ? $field['Precision'] : 0;
                            $sql_make .= "DECIMAL({$field['MaximumLength']},{$post_point})";
                    }
                    elseif ($field['DataType'] == "Boolean") {
                            $sql_make .= "CHAR(1)";
                    }
                    elseif ($field['DataType'] == "Date") {
                            $sql_make .= "DATE default '0000-00-00' not null";
                    }
                    elseif ($field['DataType'] == "Time") {
                            $sql_make .= "TIME default '00:00:00' not null";
                    }
                    else {
                            $sql_make .= "VARCHAR(255)";
                    }
    
                    $sql_make .= " COMMENT '{$cleaned_comment}'";
                    $sql_make .= ",\n";
    
                    $sql_query .= $sql_make;
            }
    
            $sql_query .= "PRIMARY KEY(`{$field_prefix}{$key_field}`) )";
    
            return $sql_query;
    
    }

  2. #2
    Join Date
    Jun 2006
    Location
    Under your bed
    Posts
    357
    ...well, I know how arrays and foreach work. It'd be easier to explain, though, if I used my own example.

    I don't know what you know, so I'm going to start with the basics. A normal variable can only have one value e.g. $name = 'Bob'; but with an array, you can make a variable have as many values as you want e.g. $names = array('Bob', 'Bill, 'Robert');

    If you want to print the value of a normal variable, just do echo $name and you're done. With an array, it is a little more complicated. PHP has to know which value you want to access, so each value has a key. In our $names array the key is 0 for 'Bob, 1 for 'Bill', and 2 for 'Robert'. We didn't give them these keys, PHP assigned them automatically. (And yeah PHP starts counting at 0.) So if we want to print out "Bill", for instance, we'd do echo $names[1];

    If we don't like keys like this, we can make our own, e.g. $user = array('username' => 'stinkypete', 'firstname' = 'Peter', 'lastname' => 'Smith'); If I want to echo this guy's first name I'd do echo $user['firstname'];

    Arrays can be more complicated than this. We can have what are called multidimensional arrays. This is an array with arrays in it! Here's an example:

    PHP Code:
    $users = array(
    '0' => array('username' => 'stinkypete''firstname' => 'Peter''lastname' => 'Smith'),
    '1' => array('username' => 'sunprincess''firstname' => 'Jasmine''lastname' => 'Hanson'),
    '2' => array('username' => 'hitsugaya''firstname' => 'Elliot''lastname' => 'Moon'),
    ); 
    (Note: You don't have to put stuff on separate lines but it makes it easier to read.)

    Anyway this multidimensional array I just showed you is similar to what you get when you query the database and have results returned. You could think of key '0' as the first row, key '1' as the second, and key '2' as the third.

    So, how does this all apply to foreach()? Well, once you start using multidimensional arrays, echoing all the values out (or doing whatever it is you want to do with them) would be annoying without foreach().


    PHP Code:
    foreach ($users as $user)
    {
        echo 
    '<strong>Username:</strong> '.$user['username'].' <strong>First Name:</strong> '.$user['firstname'].' <strong>Last Name:</strong> '.$user['lastname'].'<br />';    

    Ok, remember the keys? 0, 1, and 2? Foreach is going to go through them one by one. When it's doing a key, 0 for instance, the value of that key is going to go in $user. So, when it's doing 0, array('username' => 'stinkypete', 'firstname' => 'Peter', 'lastname' => 'Smith') gets put in $user. That's why you can do, say, echo $user['firstname'] and it will print "Peter".

    So, our little foreach here is going to print out the stuff in 0, then 1, then 2. Try it for yourself so you can see.
    Last edited by evenstar7139; 09-03-2012 at 06:51 PM.

  3. #3
    Join Date
    Aug 2004
    Location
    Ankh-Morpork
    Posts
    19,607
    If I'm understanding what you are asking (not 100% sure), I think what you want is for this section of code:
    PHP Code:
    $class "RES";
    // or set through a loop
    // pull field format information for this class
    $rets_metadata $rets->GetMetadata($resource$class);
    $table_name "rets_".strtolower($resource)."_".strtolower($class);
    // i.e. rets_property_res
    $sql create_table_sql_from_metadata($table_name$rets_metadata$rets_resource_info[$resource]['KeyField']);
    echo 
    "$sql"
    ?

    If so, it could be as simple(?) as:
    PHP Code:
    $classNames = array('RES''Foo''Bar''Etc');
    foreach(
    $classNames as $class) {
      
    // pull field format information for this class
      
    $rets_metadata $rets->GetMetadata($resource$class);
      
    $table_name "rets_".strtolower($resource)."_".strtolower($class);
      
    // i.e. rets_property_res
      
    $sql create_table_sql_from_metadata($table_name$rets_metadata,   $rets_resource_info[$resource]['KeyField']);
      echo 
    "$sql";

    "Please give us a simple answer, so that we don't have to think, because if we think, we might find answers that don't fit the way we want the world to be."
    ~ Terry Pratchett in Nation

    eBookworm.us

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Tags for this Thread

Posting Permissions

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



Recent Articles