Jump to content

[SOLVED] Accessing variables in an array().


odisey

Recommended Posts

Hello freaks!

 

        I am trying to do something that seems so simple, yet a day later I resort to your expertise.

 

        I am selecting all rows in a column in a MySQL db.  There are 8 records.  I want to sort them ramdomly and pluck the top three.  I don't just want to loop and print the results, I want to redefine each as a unique variable to pass to Flash.  The code I have here will print the results.  How do I reassign the results to unique variables? 

 

Thank you for your help. 

 

Odisey

 


<?php  #Color instrument vars
       # ODC August 4, 2008
      
require_once ('???????????.php'); //Connect to database  RESET TO SAFE PATH ONCE IT FUNCTIONS

// Define variables

$var1 = "Hello"; 

// Make selection  


$query = "SELECT images FROM movie_images ORDER BY RAND()";
$result = mysql_query($query) or die(mysql_error());

// Table

if ($result) {
   
    while ($row = mysql_fetch_array ($result, MYSQL_NUM)) {
   
   
    $s1 = $row[0];
   // $s2 = $row[1];
  //  $s3 = $row[2];  


echo '<p>'. $s1 . '</p>';
//echo '<p>'. $result . '</p>';
//echo '<p>'. $s3 . '</p>';
echo '<p>'. $var1 . '</p>';
} 

}

else {
echo 'There was a problem...';
}




mysql_close(); // Close database connection

?> 

Link to comment
Share on other sites

what is your naming scheme?

 

I would dynamically create the name for the variable within the while loop.

 

<?php
$i=1;
while ($row = mysql_fetch_array ($result, MYSQL_NUM)) {

  $varname = "var$i";   //will create a variable name: var1, var2, var3.....varn
  $i++;

  $$varname = $row[0];

  #######

  ##or use an array if you can
  
  $vars[] = $row[0];

}

?>

   

Link to comment
Share on other sites

I am getting closer, I can feel it. 

 

Here is what I am testing, and it is not working. 

 

Once I see the syntax in proper fashion, I will understand the logic. 

 

BE RIGHT BACK

 

<?php  #Color instrument vars
       # ODC August 4, 2008
      
require_once ('????.php'); //Connect to database  RESET TO SAFE PATH ONCE IT FUNCTIONS

// Define variables

$var1 = "Hello"; 

// Make selection  


$query = "SELECT images FROM movie_images ORDER BY RAND()";
$result = mysql_query($query) or die(mysql_error());

// Table

if ($result) {
   
$i=1;
while ($row = mysql_fetch_array ($result, MYSQL_NUM)) {

  $varname = "vars$i";   //will create a variable name: var1, var2, var3.....varn
  $i++;

  $varname = $row[0];

  #######

  ##or use an array if you can
  
  $vars[] = $row[0];

}

echo '<p>'. $var1 . '</p>';
//echo '<p>'. $result . '</p>';
//echo '<p>'. $s3 . '</p>';
echo '<p>'. $vars2 . '</p>';
} 



else {
echo 'There was a problem...';
}

mysql_close(); // Close database connection

?> 

Link to comment
Share on other sites

You said you wanted only 3 but I don't see anywhere in your code where you actually do that. You can add that to your query.  Also, I'm not really seeing why you are wanting to send several unique variables to flash when they all seem to be containing the same type of data.  I would suggest making one string with the values delimitated with a pipe (|) or comma (,) or something and have AS explode it when it gets it.

 

getimages.php

<?php
require_once ('????.php'); //Connect to database  RESET TO SAFE PATH ONCE IT FUNCTIONS

// you ordered by rand() now limit it to just 3
$query = "SELECT images FROM movie_images ORDER BY RAND() LIMIT 3";
$result = mysql_query($query) or die(mysql_error());

// You were using _fetch_array with the _num argument, which 
// is the exact same as using _fetch_row, so just use it
while ($row = mysql_fetch_row($result)) {
  // make an array of the images
  $info[] = $row[0];
}

// make a | delimitated string to pass to flash
$images = implode($info,"|");

// pass it to flash
echo "&images=$images"; 

?>

 

Then in flash, the code would look something like this:

 

var imagelist = new Array();
var recvars = new LoadVars();
recvars.onLoad = function(success){
     if(success){
          imagelist = this.images.split("|");
     }
}
recvars.load("getimages.php");

Link to comment
Share on other sites

you are missing the double $$.  Also do only one or the other.

 

<?php

while ($row = mysql_fetch_array ($result, MYSQL_NUM)) {

 $varname = "vars$i";   //will create a variable name: var1, var2, var3.....varn
 $i++;

$$varname = $row[0];

}
?>

echo "$var1 $var2 $var3";

 

When this code is run the first time, $varname takes the value 'var1'.  So when you call $$varname, php translates that to '$var1'.  That way you create a new variable every time the loop repeats.

 

The other option, which is more tidy and easier to work with is to use an array:

 

<?php

while ($row = mysql_fetch_array ($result, MYSQL_NUM)) {

  $var[] = $row[0];

}
?>

print_r($var);

 

This will produce a single array containing all the values for that particular column.  This is a better option, depending on how you pass the variables into flash.

Link to comment
Share on other sites

In response to Crayon violet:

 

 

This is excellent.  It is just over my head at this time.  Trying to learn here.  I had had a LIMIT 3 in an earlier version.  And decided it was not needed until I had defined the unique variables.  

 

Here is what I want to do with the data.  You said you are not sure why I want unique variables when they contain the same information.  This is one of my disconnects with learning Php.  It seems if you can create an array with many variables, you should be able to deconstruct it as well and then use each.  I am missing this...I just can't wrap the brain around it.  

 

I want to stay within a mental framework that is comprehensible to me....  Otherwise I might get something that works, I won't know why it works though.

 

I want to send three randomly chosen variables to flash.  Of course these are derived of the images column in the db.  There are eight images total.  These will be swf file names once I get this code figured out.  As you can imagine I want to load those randomly choosen file (swfs) in Flash once they are passed.  

 

I am much better on Php that AS.  Arrays make me crazy.  How to make them, use them for drop downs, etc...  np.

 

I just want to access the array in Php and create unique varialbes ($vars1, $vars2, $vars3...etc...)...so I can see it with my own two eyeballs.  This way the how why what where may finally enter my brainstem and take up residence.  

 

If I can do this GREAT! I am reading the AS Bible and I have a Joey Lott course I am taking.  More complicated AS will come soon.  

 

TY   I will save this code.

 

Is it possable to create these unique variables in Php?  

What concepts about arrays am I completely missing here?

 

TY

 

Odisey  

 

 

OK:  Let me try to rework mbeals version TY. I though the double $$ was a typo.  Almost there. 

 

   

Link to comment
Share on other sites

mbeals I got it!  with this:

 


if ($result) {
   
$i=1;
while ($row = mysql_fetch_array ($result, MYSQL_NUM)) {

  $varname = "vars$i";   //will create a variable name: var1, var2, var3....
  $i++;

$$varname = $row[0];

}

//echo "$vars1 $vars2 $vars3";

}

echo '<p>'. $vars1 . '</p>';
echo '<p>'. $vars2 . '</p>';
echo '<p>'. $vars3 . '</p>';

 

I am interested in what Crayon Violet thinks about passing these variables to flash as file names for swf movies to load.  Does this make sense -- will it work? 

 

TY for your help guys, I am getting there. 

 

Odisey

Link to comment
Share on other sites

In essence, an array is just a list of variables.  The name of the array is like the title of your list. For example, let's make a list of fruit:

 

Fruit

Apples

Oranges

Bananas

Grapes

Watermelon

Now you can make an individual variable for each fruit like so:

 

$Apples = "apple";
$Oranges = "orange";
$Bananas = "banana";
$Grapes = "grape";
$Watermelon = "watermelon";

 

But that's not very convenient coding-wise, because chances are, you're going to want to do something with those variables.  Since they have no connection except for in your own head (your own understanding of them), you're going to have to do the same thing individually to them.  For instance, if you wanted to echo out your fruit, you would have to do this:

 

echo $Apples;
echo $Oranges;
echo $Bananas;
echo $Grapes;
echo $Watermelon;

That's not very efficient.  It would be better to just make a loop, but you can't do that with individual variables.  That's one of the powers of arrays.  You can loop through your items with an array.  The array could look like this:

 

$fruit = array("apple","orange","banana","grape","watermelon");

 

Another way to write that would be:

 

$fruit[] = "apple";
$fruit[] = "orange";
$fruit[] = "banana";
$fruit[] = "grape";
$fruit[] = "watermelon";

Each time you assign something to $fruit[] it adds it to a new row in the list.  That row is called an element.  You can specify what row like this:

 

$fruit[0] = "apple";
$fruit[1] = "orange";
$fruit[2] = "banana";
$fruit[3] = "grape";
$fruit[4] = "watermelon";

 

You don't even have to go in order, and you don't even have to use numbers.  Using words instead of numbers to specify the row is called making an associative array.  This is useful for code readability.  For instance if you have an account somewhere, your account information might be stored in an array like this:

 

$account['firstname'] = "John";
$account['lastname'] = "Doe";
$account['password'] = "123abc";

 

And that is the same thing as writing it like this:

 

$account = array("firstname" => "John", "lastname" => "Doe", "password" => "123abc");

 

Each row's "name" or "label" or "identifier" (be it a word or number) is called an array key, and the data it points to is called the value  key => value.  The key goes between the [] braces.  Earlier when we did $fruit[] = "..." for each fruit, we did not specify a key.  If you do not specify a key, php will automatically assign one. If there is no previous key for $fruit, it starts at 0, and each time you assign something new, it takes the previous key and adds 1 to it.

 

Like I said earlier, one of the main advantages to arrays is being able to loop through the information.  Earlier I showed you how if you had individual variables, you would have to echo them out individually, but with your fruit in an array, you can simply do this:

 

foreach($fruit as $key => $val) {
   echo "$key $val <br />";
}

 

Since the array keys are numbers in our $fruit array, we can use a for or while loop just the same, though we would first have to find out how many fruits are on the list.  We can do this by counting them like so:

 

$count = count($fruit);
for($x = 0; $x < $count; $x++) {
   echo $fruit[$x] . "<br />";
}

That loop will go through every element of the $fruit array and echo out the value until it reaches the last element.  One other difference between a foreach loop and the other loops is that you can utilize the key as well as the value.  You cannot do this with the other loops without adding other array functions that will tell you the keys.  The foreach loop allows you to do that automatically by specifying the "..as $key => $val" in the loop's argument.  The foreach loop is mostly useful for dealing with arrays where the keys are words (associative arrays) like with the $account array example I gave, or where numbered keys are not in a traditionally countable order (like if the keys were like 0, 20, 15, 42, 88, 37 ... )

 

On that note, another advantage of arrays is that you can sort them.  Going back to our fruit array:

 

$fruit[] = "apple";
$fruit[] = "orange";
$fruit[] = "banana";
$fruit[] = "grape";
$fruit[] = "watermelon";

 

or

 

$fruit = array("apple","orange","banana","grape","watermelon");

Let's say we want to echo them out like before, but we want to echo them in alphabetical order.  PHP comes with several sorting functions and methods for sorting things based on different specifications like standard alphabetical, reverse alphabetical; there is even a way to make custom specifications, like say for instance you want to sort by how many letters in each fruit there is.  But let's just do a standard alphabetical sort:

 

$fruit = array("apple","orange","banana","grape","watermelon");
$fruit = sort($fruit);
foreach($fruit as $value) {
  echo "$value <br />";
}

 

That will output:

 

apple

banana

grape

orange

watermelon

 

And you can also nest arrays inside arrays.  Instead of making the value of an element a single piece of data, we would just start another array inside it.  This is called multi dimensional array.  You can mix and match and nest another array inside even that, making it a 3d array, the sky's the limit! But I won't really get into all that, as I think I've been more than long winded about this already.

Link to comment
Share on other sites

I am interested in what Crayon Violent thinks about passing these variables to flash as file names for swf movies to load.  Does this make sense -- will it work? 

 

TY for your help guys, I am getting there. 

 

Odisey

 

I don't really think one thing or another.  It's just data being passed.  Go for it.

Link to comment
Share on other sites

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.