database into an array indexed

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
pohontaman
Forum Newbie
Posts: 4
Joined: Thu Nov 28, 2013 10:20 pm
Location: Kinabalu, Malaysia

database into an array indexed

Post by pohontaman »

how to transform data from a database into an array indexed?
from:

$bb = mysql_query("SELECT kalori FROM bb_temp ORDER BY density DESC");
//field kalori contains=(16,12,23,13,9,10,18)

become :
Array
(
[0] => 16
[1] => 12
[2] => 23
[3] => 13
[4] => 9
[5] => 10
[6] => 18
)

Thank you...
CoursesWeb
Forum Newbie
Posts: 18
Joined: Mon Dec 09, 2013 10:52 am

Re: database into an array indexed

Post by CoursesWeb »

Hi
Try use the explode() function, example:

Code: Select all

$str = '16,12,23,13,9,10,18';
$ar_str = explode(',', $str);
// test
var_export($ar_str);
 
User avatar
pohontaman
Forum Newbie
Posts: 4
Joined: Thu Nov 28, 2013 10:20 pm
Location: Kinabalu, Malaysia

Re: database into an array indexed

Post by pohontaman »

thanks for replying.
but the contents of the field is retrieved from the database. not declared.
are there any other suggestions?
CoursesWeb
Forum Newbie
Posts: 18
Joined: Mon Dec 09, 2013 10:52 am

Re: database into an array indexed

Post by CoursesWeb »

It is easy to implement that example with data from database.
Try this (it selects one row only, for multile rows, delete "limit 1", and the numbers should be added into a two dimensional array):

Code: Select all

$bb = mysql_query("SELECT kalori FROM bb_temp ORDER BY density DESC limit 1");
$arr = array();
while ($row = mysql_fetch_array($bb)){
  $arr = explode(',', $row['kalori']);
}
// test
var_export($arr);
 
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: database into an array indexed

Post by requinix »

That latest code is close, but don't use explode() and append to $arr by using $arr[]=...
Post Reply