• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Transforming query results to the proper array

#1
[eluser]Andrewkha[/eluser]
Folks hi

Sorry for the not very self-explanatory topic title. Will try to explain here what I mean.
So when querying some table I usually get a result as 2 dimensional array:

Code:
Array
(
    [0] => Array
        (
            [id] => 1
        )

    [1] => Array
        (
            [id] => 4
        )

    [2] => Array
        (
            [id] => 24
        )
)

But to pass this further as a parameter to some function I need it to be look like single dimensional:

Code:
Array
(
    [0] => 1

    [1] =>  4

    [2] => 24
)

In order to make this happen I usually use the foreach loop. But there's a feeling that there should be an easier way to do it. Any recommendations?

Code:
foreach($results as $result) {
  $query_result[] = $result['id'];
}

#2
[eluser]InsiteFX[/eluser]
Code:
$data = array();

foreach ($results as $result)
{
    foreach ($result as $key => $value)
    {
        $data[$key] = $value;
    }
}

return $data;

#3
[eluser]Andrewkha[/eluser]
So I still need a loop for this and no way to get the data from the DB in needed format already, right?

#4
[eluser]InsiteFX[/eluser]
Correct, if you stored it in the database using a single array then it would not have been a problem.


Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  


  Theme © 2014 iAndrew  
Powered By MyBB, © 2002-2020 MyBB Group.