Click here to Skip to main content
14,664,322 members
Rate this:
Please Sign up or sign in to vote.
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]);
    }
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

Rate this:
Please Sign up or sign in to vote.

Solution 1

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.
   

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




CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100