0

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!

2
  • Why do you even want to store it that way? Making it just harder to get the information back and save new value to it. Commented Apr 8, 2016 at 5:02
  • Because i have some work pending and that totally depends on the result returned by SQL query. If its not in that form i will have to start things from begining! And i have seen that the array can be of this form! So, is there any way that i can achieve it? Commented Apr 8, 2016 at 5:10

1 Answer 1

1

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.

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

4 Comments

i knew that, this duplicacy is going to be a prob! Anyways, what if i don't have duplicate keys? Please see the Que again!
In that case you just do something like: merging the two arrays or joining them. See update in answer.
But the problem is in reading it from SQL query! How to do it from SQL query result?
Thank you so much! I got it! :)

Your Answer

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