开发者

How to manipulate arrays in PHP and MySQL?

I have a code like this.

mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("joomla") or die(mysql_error());

$result = mysql_query("SELECT id,name FROM jos_samples") or die(mysql_error());  



while($row = mysql_fetch_array( $result )) {
print_r($row);
}

And my print array is like this.

Array ( [0] => 3 [id] => 3 [1] => User1 [name] => User1 )
Array ( [0] => 4 [id] =开发者_开发百科> 4 [1] => User2 [name] => User2 ) 
Array ( [0] => 5 [id] => 5 [1] => User3 [name] => User3 ) 
Array ( [0] => 6 [id] => 6 [1] => User4 [name] => User4 ) 

I want this array something like this

Array ( [3] => User1 [4] => User2 [5] => User3 [6] => User4 )

How can I proceed?


You can reshape your array:

/* ... */

$rows = array();
while($row = mysql_fetch_array($result)) {
    $rows[$row['id']] = $row['name'];
}

$rows is your result.


If I get this right, you want:

while($row = mysql_fetch_array( $result, MYSQL_ASSOC )) {

http://php.net/manual/en/function.mysql-fetch-array.php

(You're currently using the default, which is MYSQL_BOTH.

And then you need to rework your array:

$rows = array();
while($row = mysql_fetch_array( $result, MYSQL_ASSOC )) {
  $rows[$row['id']] = $row['name'];
}


Try this, it builds an array containing the usernames as you want it.

$aUsers = array();

// Use _assoc, it filters numeric key's.
while($aRow = mysql_fetch_assoc( $result )) {
    $aUsers[$aRow['id']] = $aRow['name'];
}

echo '<pre>';
print_r($aUsers);


Then dont ask for the ID to be returned in your query, the reason you get 2 items is because ID is in there, secondly if you dont want the name of the field, change the request for the fetch array to

mysql_fetch_array ($result, MYSQL_NUM)

this only gets numbers not the name of the field


while($row = mysql_fetch_array( $result )) {
$array[$row['id']] = $row['name'];
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜