0

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?

5 Answers 5

3

You can reshape your array:

/* ... */

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

$rows is your result.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot man.. This worked. Thank you again.. Out of words
3

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

Comments

2

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

3 Comments

I think the asker wants the mysql field id to represent the array's key.
@proximus, that's what this does
@proximus I edited it the second after I posted it :) you were correct!
1

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

1 Comment

If you just want to print the id and name, then you can do a foreach rather than print_r, you control exactly how and what you see then.
1
while($row = mysql_fetch_array( $result )) {
$array[$row['id']] = $row['name'];
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.