2

I have an array that looks like this:

array:9 [▼
  0 => {#279 ▼
    +"id": "103"
    +"name": "In what city did you meet your spouse/partner?"
  }
  1 => {#280 ▼
    +"id": "100"
    +"name": "What is the first name of the person you first kissed?"
  }
  2 => {#281 ▼
    +"id": "102"
    +"name": "What is the name of your favorite childhood friend?"
  }
  3 => {#282 ▶}
  4 => {#283 ▶}
  5 => {#284 ▶}
  6 => {#285 ▶}
  7 => {#286 ▶}
  8 => {#287 ▶}
]

This is the dd(). I'm wondering how it might be possible to transform it into a key/value array, using the id as the key and the name as the value. Something like this:

array(
  '103' => 'In what city did you meet your spouse/partner?',
  '100' => 'What is the first name of the person you first kissed?'
);
Matt Larsuma
  • 1,456
  • 4
  • 20
  • 52

3 Answers3

7

As of PHP 7, you can use array_column() on objects, with the third parameter as the column to index by...

$questions = array_column($data, "name", "id");
Nigel Ren
  • 56,122
  • 11
  • 43
  • 55
1

You can use a collections pluck method:

$collection = collect($array)->pluck("name","id");

If you want to get an array back use:

$collection->all();
apokryfos
  • 38,771
  • 9
  • 70
  • 114
0

I figured it out with:

$data = DB::connection()->select($sql);

$questions = [];

foreach ($data as $question) {
    $questions[$question->id] = $question->name;
}

Open to any slicker solutions, but this definitely works!

Matt Larsuma
  • 1,456
  • 4
  • 20
  • 52