dafydd Posted May 24, 2007 Share Posted May 24, 2007 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 Quote Link to comment https://forums.phpfreaks.com/topic/52817-dynamically-name-an-array-or-any-variable-for-that-matter/ Share on other sites More sharing options...
per1os Posted May 24, 2007 Share Posted May 24, 2007 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); ?> Quote Link to comment https://forums.phpfreaks.com/topic/52817-dynamically-name-an-array-or-any-variable-for-that-matter/#findComment-260758 Share on other sites More sharing options...
kenrbnsn Posted May 24, 2007 Share Posted May 24, 2007 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 Quote Link to comment https://forums.phpfreaks.com/topic/52817-dynamically-name-an-array-or-any-variable-for-that-matter/#findComment-260764 Share on other sites More sharing options...
dafydd Posted May 24, 2007 Author Share Posted May 24, 2007 Thanks both. frost110 - Its for a function i need to use on a shop site with some difficult legacy code. Cheers Dafydd Quote Link to comment https://forums.phpfreaks.com/topic/52817-dynamically-name-an-array-or-any-variable-for-that-matter/#findComment-260773 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.