Jump to content

Dynamic array list?


ven.ganeva

Recommended Posts

Hi is it possible to create a dynamic array list? At the moment I have a script with some code like this in it:

 

$example_data = array(
     array('a',3),
     array('b',5),
     array('c',7)
);

 

Now I want to change this array list to consist of data from a database. I have the following code so far (I'm not a hardcore PHP coder or anything) and would appreciate any help or advice as to how I can continue with it...

 

mysql_select_db($database_conn_imni, $conn_imni);
$query_rs = "SELECT `year`, metric_tons FROM tbl_data_annual";
$rs = mysql_query($query_rs, $conn_imni) or die(mysql_error());

$arrays = "";
do {
$arrays.="array('". $row_rs['year']."',". $row_rs['metric_tons']."),";
} while ($row_rs = mysql_fetch_assoc($rs)); 
$arrays=substr($arrays,0,-1); // to remove last comma

 

 

 

 

Link to comment
Share on other sites

Im a bit confused as to what you want your array to contain? Is it supposed to be like:

 

$example_data = array(

    array(year,metric tons),

    array(year2,metric tons2),

);

 

If so, try:

 

<?php
mysql_select_db($database_conn_imni, $conn_imni);
$query_rs = "SELECT `year`, metric_tons FROM tbl_data_annual";
$rs = mysql_query($query_rs, $conn_imni) or die(mysql_error());
$array = array();
while(list($year,$tons) = mysql_fetch_row($rs)){
	$array[] = array($year,$tons);
}
echo '<pre>'.print_r($array,1).'</pre>';//lets check the output to make sure its what we ned
?>

Link to comment
Share on other sites

<?php
mysql_select_db($database_conn_imni, $conn_imni);
$query_rs = "SELECT `year`, metric_tons FROM tbl_data_annual";
$rs = mysql_query($query_rs, $conn_imni) or die(mysql_error());
$array = array();
while(list($year,$tons) = mysql_fetch_row($rs)){
	$array[] = array($year,$tons);
}
echo '<pre>'.print_r($array,1).'</pre>';//lets check the output to make sure its what we ned
?>

 

This is great and it works but I just noticed that it starts at the second record and misses the first. Is this a problem with the while loop? How else can I do the loop? Thanks for an help in advance.

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.