hjaffer2001 hjaffer2001 -4 years ago 49
MySQL Question

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?

Answer Source

You can reshape your array:

/* ... */

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

$rows is your result.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download