tags:

views:

29

answers:

2

Hi,

I am having trouble at creating a specific array. What i want is to pull the info for my members (from mysql database) and then store them to an array. The array should be like this:

$members = array(
'John' => array('avatar' => '/images/avatar/ji.jpg', 'country' => 'uk.'),
'Nick' => array('avatar' => '/images/avatar/nick.jpg', 'country' => 'italy.'),
);

etc.. so i pull the name,avatar url and country from the db and then i store them in to the previous array. My question is, how could i create this array?

Thanks in advance!

About creating an array at php.

+3  A: 

Something like this should work:

$members = array();
$q = mysql_query("SELECT name , avatar, country from table");
while($row = mysql_fetch_assoc($q)){
   $array = array("avatar" => $row['avatar'] , "country" => $row['country']);
   $members[$row['name']] = $array;
}
Sabeen Malik
it works! thanks a lot! :)
Manolis
You can even do it in one line within the while loop: `$members[$row['name']] = array("avatar" => $row['avatar'] , "country" => $row['country']);`
Kau-Boy
Sometimes you just need to lay things out based on the target audience :)
Sabeen Malik
A: 

Using PDO:

$members = array();
$conn = new PDO("mysql:host=$host;dbname=$database", $username, $password);
$sql = "SELECT name, avatar, country FROM members";
foreach ($conn->query($sql) as $row) {
    $temp = array('avatar' => $row['avatar'], 'country' => $row['country']);
    $members[$row['name']] = $temp;
}
Vinko Vrsalovic
And what's the advantage of using PDO for that? It also works with "pure MySQL".
Kau-Boy
PDO is more flexible than pure MySQL, and prepared statements are easier to work with. It's not that PDO is better to answer the question, was just to present the OP with an alternative :). Besides, I had already started to write the answer when Sabeen's appeared (in fact, I upvoted him.)
Vinko Vrsalovic