3

Hey, I'm using FuelPHP and doing like this...

$query =
  \DB::select( 'username' )
    ->from( 'users' )
    ->execute()
    ->as_array();

I'm getting array as shown below.

Array
(
  [0] => Array
  (
    [username] => daGrevis
  )

  [1] => Array
  (
    [username] => whatever
  )

  [2] => Array
  (
    [username] => foobar
  )

)

It's definitely not what I need. Here's example of "ideal array" for me:

Array
(
  [0] => daGrevis
  [1] => whatever
  [2] => foobar
)

So how can I get "ideal array"? Maybe I do something wrong in the query... if no... how can I convert array #1 to array #2? Using loops maybe? Or there is built-in function? I'm confused.

daGrevis
  • 21,014
  • 37
  • 100
  • 139
  • 1
    That's the problem with bad frameworks reinventing the wheel. In PDO you would write `->fetchAll(PDO::FETCH_COLUMN, 0)`. – NikiC Mar 27 '11 at 14:21
  • @nikic Are you speaking about Fuel or all PHP frameworks in general? If only about Fuel... then it's okey for it, because it's only in beta. ) – daGrevis Mar 27 '11 at 17:35
  • I'm talking about any framework, which, instead of simply using the very well designed interfaces that PDO provides, uses some reimplementation using mysqli/mysql. – NikiC Mar 27 '11 at 18:28
  • This is nothing to do with frameworks, this is how native MySQL bindings return the data by default. We can add a method in to return arrays like that easily enough but there are plenty of insanely simple solutions to this basic array structure issue that have been around for decades. – Phil Sturgeon Mar 27 '11 at 21:13
  • See as well: [Turning multidimensional array into one-dimensional array](http://stackoverflow.com/questions/8611313/turning-multidimensional-array-into-one-dimensional-array) – hakre Jan 06 '12 at 08:17

3 Answers3

11

You can do this with Fuel natively:

$query = \DB::select( 'username' )
           ->from( 'users' )
           ->execute()
           ->as_array(null, 'username');

This will return exactly what you want.

Dan Horrigan
  • 1,275
  • 7
  • 8
4

Yep, a foreach loop should do the trick:

$new_array = array();
foreach($query as $result_num => $sub_array)
{
    $new_array[$result_num] = $sub_array[username];
}
luciddreamz
  • 2,073
  • 14
  • 15
2

Do a foreach loop to convert it, something like this:

$arr2 = array();
foreach ($arr1 as &$value) {
array_push($arr2, $value[username]);
}
Kristoffer la Cour
  • 2,591
  • 3
  • 25
  • 36