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
https://forums.phpfreaks.com/topic/77013-dynamic-array-list/
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
https://forums.phpfreaks.com/topic/77013-dynamic-array-list/#findComment-389976
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
https://forums.phpfreaks.com/topic/77013-dynamic-array-list/#findComment-394554
Share on other sites

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.