开发者

About creating an array at php

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 st开发者_开发知识库ore them in to the previous array. My question is, how could i create this array?

Thanks in advance!

About creating an array at php.


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;
}


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;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜