Jump to content

Dynamically name an array (or any variable for that matter)


dafydd

Recommended Posts

Hi,

 

I am trying to create a series of arrays from a database using a while loop.  I want to end up with $array1, $array2, $array3....$arrayn.

 

 

In the code below i have used ".$n" to illustrate what i am trying to do but i know that this isn't the way :-)

 

$sql_offers = "SELECT * FROM special_offers";
	$result_offers = mysql_query($sql_offers);
    if (mysql_num_rows($result_offers) > 0)
	{
$n='1';
	while($row_offers = mysql_fetch_array($result_offers))
		{
   $array_offers[]=$row_offers['p_id'];
   $array_offers[]=$row_offers['offer_id'];
   $array_offers[]=$row_offers['description'];
   $array_offers[]=$row_offers['added'];
   $array_offers[]=$row_offers['discount'];
$n++;
		}
    }

 

Any ideas?

 

Thanks

 

Dafydd

No clue why, but ok

 

<?php
$sql_offers = "SELECT * FROM special_offers";
	$result_offers = mysql_query($sql_offers);
    if (mysql_num_rows($result_offers) > 0)
	{
$n=1;
	while($row_offers = mysql_fetch_array($result_offers))
		{
                           $array_name = 'array'.$n;
   $$array_name = $row_offers;
$n++;
		}
    }

echo print_r($array1);
?>

I would use a two-dimensional array instead of many arrays:

<?php
$sql_offers = "SELECT * FROM special_offers";
$result_offers = mysql_query($sql_offers);
$n=0;
if (mysql_num_rows($result_offers) > 0){
   while($row_offers = mysql_fetch_array($result_offers)) {
       $array_offers[$n] = array();
       $array_offers[$n][]=$row_offers['p_id'];
       $array_offers[$n][]=$row_offers['offer_id'];
       $array_offers[$n][]=$row_offers['description'];
       $array_offers[$n][]=$row_offers['added'];
       $array_offers[$n][]=$row_offers['discount'];
       $n++;
   }
}
?>

Doing it this way makes it much easier to use later in your code.

 

Ken

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.