Click here to Skip to main content
15,076,465 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 ?
PHP
$arr = array($row1["col1"]=>$row1["col2"],$row2["col1"]=>$row2["col2"],$row3["col1"]=>$row3["col2"]);


What I have tried:

PHP
$sql = mysql_query("select * from test");
$arr = array();
while($ = mysql_fetch_array($sql)){
       $arr[] = array($r[col1]=> $r[col2]);
    }
Posted
Updated 6-Sep-20 2:25am
v2
Comments
Sandeep Mewara 4-Sep-20 17:06pm
   
Your array structure is not clear. What do you mean by:
$row1["col1"]=>$row1["col2"]
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:
PHP
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.
   

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