简体   繁体   中英

Storing returned result from sql query in the form of array

I am trying to store the result of SQL query in an array.I am not able to use that result,however i can print it using print_r() method of php and it is printing-

Array
(
    [0] => Array
        (
            [SNO] => 1
            [chartType] => pie
            [outputValues] => rural_total_m,urban_total_m
            [attributeId] => 10025
            [level] => india
        )
)

I want it to store in a variable or a file in the form of--

Array(      
       SNO => 1,
       chartType => pie,
       outputValues => rural_total_m,urban_total_m,
       attributeId => 10025,
       level => india
    )

I have tried few thing but nothing like i want till now! :( Thank You!

Really not sure why you will need this type of things -- but technically it is not possible -- an array cannot have 2 keys with same name / same key twice . So you can't do this.

UPDATE:

In case of duplicate keys to be managed - you can do something like:

Store the query result in $result

   $result = array();
   $sql = mysql_query("... your sql ...");
   while ($row = mysql_fetch_array($res))
   {
      $result[] = $row;
   }

Say this is how the $result looks like:

Array
(
    [0] => Array
        (
            [SNO] => 1
            [chartType] => pie
            [outputValues] => rural_total_m,urban_total_m
            [attributeId] => 10025
            [level] => india
        )
)

Now parse it following way (or you can do it any other way like foreach, map, etc.)

$output = array();
array_walk($result, function ($value, $key) use (&$output) {
    // here the $value is the single array you are looking for. 
    $output[] = $value;
});

print_r($output);

This will do.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM