Click here to Skip to main content
15,668,923 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
How to get mysql data in following structure in php ?
$arr = array($row1["col1"]=>$row1["col2"],$row2["col1"]=>$row2["col2"],$row3["col1"]=>$row3["col2"]);

What I have tried:

$sql = mysql_query("select * from test");
$arr = array();
while($ = mysql_fetch_array($sql)){
       $arr[] = array($r[col1]=> $r[col2]);
Updated 6-Sep-20 2:25am
Sandeep Mewara 4-Sep-20 17:06pm    
Your array structure is not clear. What do you mean by:
Richard MacCutchan 6-Sep-20 8:31am    
It's PHP array syntax.

1 solution

Your loop to retrieve the data from the data object is a bit of a mess:
while($ = mysql_fetch_array($sql)) {
       $arr[] = array($r[col1]=> $r[col2]);
Unless you defined them as a fixed value, col1 and col2 are not valid indices. I suspect you left out the quotes (which you do use in yours what-you-want example.

I also suppose you meant $r and not just $ in you r while conditional test.

Also, if you wish to use one value as the array index, a guess at what you mean in the 'what I want' example, you'd likely want the content of the loop to look more like:

$arr[$r['col1']] = $r['col2']);

For a start.
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900