开发者

Making username and userid into an array

开发者 https://www.devze.com 2022-12-24 13:38 出处:网络
I want to my array, somthing like this: array(\"userid\"=>\"username\",\"1\"=>\"ganeshfriends\",\"2\"=>\"tester\")

I want to my array, somthing like this:

array("userid"=>"username","1"=>"ganeshfriends","2"=>"tester")
开发者_Go百科

mysql query something like this:

$query = select username, userid from tbluser

$result = mysql_query($query);

while($row = mysql_fetch_array($result)){
    $items = array($row['userid']=>$row['username']);
}
print_r($items);

How can I make userid as key and username as val?


Try this:

$query = "select username, userid from tbluser";

$result = mysql_query($query);
$items=array();
while($row = mysql_fetch_array($result)){
    $items[$row['userid']]=$row['username'];
}
print_r($items);

The problem is that you delete and reassign the result array ($items) in every loop of the while block


Since everyone keeps suggesting the same thing, I figure I may as well join in.

When I have a situation with keys from sql values, I like to set them to variables first so it's nicer looking:

$query = "select username, userid from tbluser";

$result = mysql_query($query);

while($row = mysql_fetch_array($result)){
    $userid = $row['userid'];
    $username = $row['username']
    $items[$userid] = $username;
}
print_r($items);

It may add two lines, but it sure is easier on the eyes and avoids brackets in brackets.


You can do:

$arr = array('userid' => 'username');

$result = mysql_query($query);
if(!$result) die("Query failed");

while($row = mysql_fetch_array($result)){
  $arr[$row['userid']] = $row['username'];
}


Use other variables, like Anthony, i just want to say, don't remember about stripslashes(i think you've done mysql_real_escape_string() when writing them to tha database)


while($row = mysql_fetch_array($result)){
    $userid = $row['userid'];
    $username = stripslashes($row['username']);
    $items[$userid] = $username;
}


since youre only using associative access i would propose the use of mysql_fetch_assoc() instead of mysql_fetch_array()

since you don't arg that you want an associative array given back by mysql_fetch_array() it creates 2 arrays, one with int-indexes and one with string-indexes (assoc[iative]), even though this short script doesn't use much memory and might have high speed, you should always remember the performance.

0

精彩评论

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