Jump to content

How to increase a variable name by 1 on each loop?


Go to solution Solved by tech0925,

Recommended Posts

Hello everyone :)

 

I am trying to figure out how in the world I can increase the actuall variables name by 1 on each loop. Any help would be much appreciated. Let me show an example of what I want and then explain why I was trying to do this.

 

Ok my database query will perform 20 loops retrieving some info and placing them into variables. Lets say I have the following variable.

$thisAddress = MYSQL_RESULT($result,$i,"address");

So this will repeat 20 times and it will actually contain an address. What I need to do is make the variable unique for each address. For example:

$thisAddress1
$thisAddress2

and so on

 

Here is why. I am using google maps to display 20 address markers for each page. Here is what my google maps script looks like:

<script type="text/javascript">
if (GBrowserIsCompatible()) {

    var map = new GMap2(document.getElementById("map_canvas"));
    map.setUIToDefault();
    
    // Create a base icon for all of our markers that specifies the
    // shadow, icon dimensions, etc.
    var baseIcon = new GIcon(G_DEFAULT_ICON);
    baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
    baseIcon.iconSize = new GSize(20, 34);
    baseIcon.shadowSize = new GSize(37, 34);
    baseIcon.iconAnchor = new GPoint(9, 34);
    baseIcon.infoWindowAnchor = new GPoint(9, 2);

    // Creates a marker whose info window displays the letter corresponding
    // to the given index.
    function createMarker(point, index) {
      // Create a lettered icon for this point using our icon class
      var letter = String.fromCharCode("A".charCodeAt(0) + index);
      var letteredIcon = new GIcon(baseIcon);
      letteredIcon.image = "http://www.google.com/mapfiles/marker" + letter + ".png";

      // Set up our GMarkerOptions object
      markerOptions = { icon:letteredIcon };
      var marker = new GMarker(point, markerOptions);

      GEvent.addListener(marker, "click", function() {
        marker.openInfoWindowHtml(addresses[index]);
      });
      return marker;
    }

 
  // ====== Create a Client Geocoder ======
  var geo = new GClientGeocoder();

  // ====== Array for decoding the failure codes ======
  var reasons=[];
  reasons[G_GEO_SUCCESS]            = "Success";
  reasons[G_GEO_MISSING_ADDRESS]    = "Missing Address: The address was either missing or had no value.";
  reasons[G_GEO_UNKNOWN_ADDRESS]    = "Unknown Address:  No corresponding geographic location could be found for the specified address.";
  reasons[G_GEO_UNAVAILABLE_ADDRESS]= "Unavailable Address:  The geocode for the given address cannot be returned due to legal or contractual reasons.";
  reasons[G_GEO_BAD_KEY]            = "Bad Key: The API key is either invalid or does not match the domain for which it was given";
  reasons[G_GEO_TOO_MANY_QUERIES]   = "Too Many Queries: The daily geocoding quota for this site has been exceeded.";
  reasons[G_GEO_SERVER_ERROR]       = "Server error: The geocoding request could not be successfully processed.";
  reasons[403]                      = "Error 403: Probably an incorrect error caused by a bug in the handling of invalid JSON.";
 
  var j=0;
  // ====== Geocoding ======
  function getAddress(search, next) {
    geo.getLocations(search, function (result)
      {
        // If that was successful
        if (result.Status.code == G_GEO_SUCCESS) {
          // Lets assume that the first marker is the one we want
          var p = result.Placemark[0].Point.coordinates;
          var lat=p[1];
          var lng=p[0];
          if(j == 0)
          {
            map.setCenter(new GLatLng(lat, lng), 15);
          }

            var latlng = new GLatLng(lat, lng);
            map.addOverlay(createMarker(latlng, j));
          
        }
        j++;
        next();
      }
    );
  }


  // ======= An array of locations that we want to Geocode ========
  addresses =   [
        "<?php echo $thisAddress1; ?>",
        "<?php echo $thisAddress2; ?>",
        "<?php echo $thisAddress3; ?>",
        "<?php echo $thisAddress4; ?>",
        "<?php echo $thisAddress5; ?>",
        "<?php echo $thisAddress6; ?>",
        "<?php echo $thisAddress7; ?>",
        "<?php echo $thisAddress8; ?>",
        "<?php echo $thisAddress9; ?>",
        "<?php echo $thisAddress10; ?>",
        "<?php echo $thisAddress11; ?>",
        "<?php echo $thisAddress12; ?>",
        "<?php echo $thisAddress13; ?>",
        "<?php echo $thisAddress14; ?>",
        "<?php echo $thisAddress15; ?>",
        "<?php echo $thisAddress16; ?>",
        "<?php echo $thisAddress17; ?>",
        "<?php echo $thisAddress18; ?>",
        "<?php echo $thisAddress19; ?>",
        "<?php echo $thisAddress20; ?>",
        ];

  // ======= Global variable to remind us what to do next
  var nextAddress = 0;

  // ======= Function to call the next Geocode operation when the reply comes back

  function theNext() {
    if (nextAddress < addresses.length) {
      getAddress(addresses[nextAddress],theNext);
      nextAddress++;
    }
  }

  // ======= Call that function for the first time =======
  theNext();

}

// display a warning if the browser was not compatible
else {
  alert("Sorry, the Google Maps API is not compatible with this browser");
}

</script>

Is this the best way to do this or does anyone have a better idea?

 

Thanks!!!

Edited by tech0925

the direct answer to your question is that you DON'T use an incrementing series of variable names. you use an array where the index is what increments.

 

What about doing something like this?

$i = 1;
$thisAddress?><php echo $1; ?> <?php = MYSQL_RESULT($result,$i,"address");
$i++;

Would that even work?

 

I am just trying to figure out how to insert the 20 addresses on each page into that google map script.

 

Any thoughts?

What about doing something like this?

...

Would that even work?

No, it wouldn't. There is a way to do it known as variable-variables, however as mentioned it is the wrong solution. What you should do is store everything into an array. For example:

 

$addressList=array();
for ($i=0; $i<20; $i++){
   $addressList[$i] = mysql_result($result, $i, 'address');
}

should produce your existing output (you had an extra , at the end of your existing output that was not valid) -

  addresses =   [
    <?php
    echo '"';
    echo implode('","',$addressList);
    echo '"';
    ?>
        ];

 

  // ======= An array of locations that we want to Geocode ========
  addresses =   [
        "<?php echo $thisAddress1; ?>",
        "<?php echo $thisAddress2; ?>",
        "<?php echo $thisAddress3; ?>",
        "<?php echo $thisAddress4; ?>",
        "<?php echo $thisAddress5; ?>",
        "<?php echo $thisAddress6; ?>",
        "<?php echo $thisAddress7; ?>",
        "<?php echo $thisAddress8; ?>",
        "<?php echo $thisAddress9; ?>",
        "<?php echo $thisAddress10; ?>",
        "<?php echo $thisAddress11; ?>",
        "<?php echo $thisAddress12; ?>",
        "<?php echo $thisAddress13; ?>",
        "<?php echo $thisAddress14; ?>",
        "<?php echo $thisAddress15; ?>",
        "<?php echo $thisAddress16; ?>",
        "<?php echo $thisAddress17; ?>",
        "<?php echo $thisAddress18; ?>",
        "<?php echo $thisAddress19; ?>",
        "<?php echo $thisAddress20; ?>",
        ];

 

would become simply:

  addresses = <?php echo json_encode($addressList); ?>;

You guys rock! One final question..

 

Here is my loop

                    $thisAddress[$i] = mysql_result($result, $i, 'address');
                    $thisCity[$i] = MYSQL_RESULT($result,$i,"city");
                    $thisState[$i] = MYSQL_RESULT($result,$i,"state");
                    $thisZip[$i] = MYSQL_RESULT($result,$i,"zip");

Then how can I make the variable $addressList to contain this arrays? Then use that in the script?

$addressList = "$thisAddress[], $thisCity[], $thisState[] $thisZip[]";

Is that right? Also, I need to make this variable outside the loop right?

 

 

Thanks again for the help!!!!!!!!!!

Just put that variable in your declaration

 

and use $addressList instead of creating new variables

$addressList[$i]['address'] = mysql_result($result, $i, 'address');

Then you will have something like

$addressList[5]['address']  to get the address for the fourth result.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.