2

I often have a need for making a database query where the key of resulting array is the value of the first column specified in the SQL (instead of the key just being an auto-assigned incremental number as the array is being filled). Is that possible without having to rework the array manually afterwards?

I know there is queryAll(PDO::FETCH_KEY_PAIR) but that only works for two colums (the array value is a single database column instead of a sub-array of all the remaining columns)

So, instead of:

array (
  0 => 
    array (
      'id' => 6955,
      'firstname' => 'John',
      'lastname' => 'Doe',
      'country' => 'United States',
    ),
  1 => 
    array (
      'id' => 8588,
      'firstname' => 'Helen',
      'lastname' => 'Smith',
      'country' => 'Denmark',
    ),
)

...I need:

array (
  6955 => array (
    'firstname' => 'John',
    'lastname' => 'Doe',
    'country' => 'United States',
  ),
  8588 => array (
    'firstname' => 'Helen',
    'lastname' => 'Smith',
    'country' => 'Denmark',
  ),
)

It doesn't necessarily have to be arrays - it could made of objects as well. It is just the structure that is important.

1
  • Could you give an example of expected result? Commented Aug 1, 2016 at 11:15

1 Answer 1

5

You can use indexBy() for this (it will not skip the chosen column in results but I think this is not a problem).

Example:

$query = (new \yii\db\Query())
    ->from('user')
    ->limit(10)
    ->indexBy('id')
    ->all();

returns [
    100 => ['id' => 100, 'username' => '...', ...], 
    101 => [...], 
    103 => [...], 
    ...
]

See the guide for more info.

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

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.